【问题标题】:Running function of one application from within another application从另一个应用程序中运行一个应用程序的功能
【发布时间】:2013-08-22 23:59:22
【问题描述】:

我有两个独立的应用程序: 第一个:

    Namespace FirstApplication
        Class MainWindow
            Public Sub New()
                InitializeComponent()
            End Sub

            Public Function RunBatch(Parameter as String) as Double
                'Do some work
                Return SomeValue
            End Function

        End Class
    End Namespace

第二次申请:

    Namespace SecondApplication
        Class MainWindow
            Public Sub New()
                InitializeComponent()
            End Sub

            Public Sub RunBatch()
                'Call RunBatch() from first Application, get show the result
                Msgbox(RunBatch)
            End Function

        End Class
    End Namespace

两者都是基于 WPF、.Net 4.0 的。目标是在第一个应用程序上调用第二个应用程序并在其中执行一个函数。

关键部分是这两个应用程序主要是独立使用的,并且偶尔会在第一个应用程序上进行第二次调用。因为这两个应用程序都需要作为可执行文件存在,所以我不想通过创建第一个应用程序的 dll 来解决问题 - 我需要将可执行文件和 dll 更新保持到最新状态,如果它们不同步,可能会造成灾难性后果.

所以问题是是否有可能在第二个应用程序的 AppDomain 中创建第一个应用程序的实例,并且至关重要的是,执行该实例的功能。

【问题讨论】:

  • 最好的办法是将方法放在一个库中,并从您想要使用它的应用程序中引用。
  • 正确的解决方案当然是将通用功能提取到类库中。任何其他选项比那样做更多的工作和更难维护。
  • 我完全同意库将是最好的,但我以前对需要频繁(一天多次)修改的库有过困难的开发经验。我应该阅读在 VS 中调试 dll。

标签: vb.net appdomain


【解决方案1】:

我不相信您可以在另一个 AppDomain 中创建一个 AppDomain。

您拥有的任何其他选项(使用 WCF,或旧式 .NET Remoting,或跨 AppDomains)都将比仅创建两个应用程序都可以引用的单个 DLL 更复杂。只要您不更改共享 DLL 的程序集号,如果您对 DLL 进行更改(假设您没有进行诸如更改方法签名之类的重大更改),您就不必重新编译每个 exe。

FirstApplication 必须对 SecondApplication 做些什么吗?您是否试图从另一个应用程序控制一个应用程序的功能?如果是这样,您将需要 WCF 之类的东西(使用命名管道或仅使用自托管 Web 服务)。或者只是想不必两次编写相同的代码?那么最简单的方法可能是创建一个 DLL 两个应用程序引用。

【讨论】:

  • 反射似乎是最简单的方法,我将不得不调查 WCF,因为我从未使用过它。谢谢指点。
【解决方案2】:

显然,这可以通过反射来完成。这个过程很简单,虽然不如使用 dll 方便。

Public Class CalltoExternallApp
'this is the declaration of the external application you want to run within your application
Dim newAssembly As System.Reflection.Assembly = System.Reflection.Assembly.LoadFrom("Mydirectory\Myfile.exe")
Public Sub Main()
            'Loads the main entry point of the application i.e. calls default constructor and assigns handle for it to MyApplication
            Dim MyApplication = newAssembly.CreateInstance("MyApplication.RootClass")
            'Get the type which will allow for calls to methods within application
            Dim MyApplicationType as Type = newAssembly.GetType("MyApplication.RootClass")
            'If calling a function, the call will return value as normal. 
            Dim Result As Object = LunaMain.InvokeMember("MyFunction", Reflection.BindingFlags.InvokeMethod, Nothing, MyApplication, MyParameters)
End Sub
End Class

还可以在这里查看是否将事件处理程序添加到通过反射创建的实例: http://msdn.microsoft.com/en-us/library/ms228976.aspx

【讨论】:

    猜你喜欢
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多