Vb.net 从另一个应用程序中运行一个应用程序的功能
我有两个独立的应用程序: 第一个:Vb.net 从另一个应用程序中运行一个应用程序的功能,vb.net,appdomain,Vb.net,Appdomain,我有两个独立的应用程序: 第一个: Namespace FirstApplication Class MainWindow Public Sub New() InitializeComponent() End Sub Public Function RunBatch(Parameter as String) as Double 'Do
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、.NET4.0的。目标是在第一个应用程序上调用第二个应用程序,并在其中执行一个函数
关键的一点是,这两个应用程序主要是独立使用的,只有偶尔在第一个应用程序上进行第二次调用。因为这两个应用程序都需要作为可执行文件存在,所以我不想通过创建第一个应用程序的dll来解决这个问题-我需要将可执行文件和dll更新保持到最新状态,如果它们不同步,可能会造成灾难性的后果
所以问题是,是否有可能在第二个应用程序的AppDomain中创建第一个应用程序的实例,关键是执行该实例的功能。我不相信您可以在另一个应用程序域中创建一个应用程序域 您拥有的任何其他选项(使用WCF、老式的.NET远程处理或跨应用程序域)都将比创建两个应用程序都可以引用的单个DLL更复杂。只要不更改共享DLL的程序集编号,如果对DLL进行更改,就不必重新编译每个exe(假设不进行破坏性更改,如更改方法签名)
第一个应用程序必须对第二个应用程序做些什么吗?您是否试图从一个应用程序控制另一个应用程序的功能?如果是这样,您将需要类似WCF的东西(使用命名管道或仅使用自托管web服务)。或者只是尝试不必编写两次相同的代码?然后,最简单的方法可能是创建一个DLL,供两个应用程序引用。显然,这可以通过反射完成。这个过程很简单,尽管不如使用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
还请检查此处,以将事件处理程序添加到通过反射创建的实例:
最好将方法放入库中,并从要使用它的应用程序中引用。正确的解决方案当然是将常用功能提取到类库中。任何其他的选择都会比那样做要困难得多,维护起来也会困难得多。我完全同意library是最好的,但我以前有过关于需要频繁(一天多次)修改的库的开发经验。我应该仔细阅读一下在VS中调试DLL。反射似乎是最简单的方法,我必须研究WCF,因为我从未使用过它。谢谢你的指点。