我想你需要用它自己的 .config 文件加载一个单独的程序集,不是吗?我这样做的一种方法是将程序集加载到新的 AppDomain 中。您可以将该程序集部署在一个单独的文件夹中,其中包含他所需的所有引用。
首先设置AppDomain,这里有一个方法:
AppDomain getAppDomainForAssembly(string assemblypath, string appdomainname)
{
//this._assembly_file = AssemblyFile;
string _assembly_file_name = System.IO.Path.GetFileName(assemblypath);
string _rootpath = System.IO.Path.GetDirectoryName(assemblypath);
//this._assembly_class_name = AssemblyClassNameToInstance;
AppDomainSetup _app_domain_info = new AppDomainSetup();
_app_domain_info.ApplicationBase = _rootpath;
_app_domain_info.PrivateBinPath = _rootpath;
_app_domain_info.PrivateBinPathProbe = _rootpath;
_app_domain_info.ConfigurationFile = _rootpath + @"\app.config"; //Here put the path to the correct .assembly .config file
AppDomain _app_domain = AppDomain.CreateDomain(
appdomainname, null, _app_domain_info);
return _app_domain;
}
然后获取在程序集上执行该方法的对象的实例:
protected System.Reflection.Assembly _asm_resolve(string assemblyFile)
{
return System.Reflection.Assembly.LoadFrom(assemblyFile);
}
object getInstanceFromAppDomain(ref AppDomain appDomain,
string assemblyPath, string className = null)
{
if (string.IsNullOrEmpty(className))
{
System.Reflection.Assembly assembly = _asm_resolve(assemblyPath);
System.Reflection.MethodInfo method = assembly.EntryPoint;
return appDomain.CreateInstanceFromAndUnwrap(assemblyPath, method.Name);
}
else
{
return appDomain.CreateInstanceFromAndUnwrap(assemblyPath, className);
}
}
即使我们知道对象类型,我们也可以创建一个泛型类型的方法:
T getInstanceFromAppDomain<T>(ref AppDomain appDomain,
string assemblyPath, string className = null)
{
if (string.IsNullOrEmpty(className))
{
System.Reflection.Assembly assembly = _asm_resolve(assemblyPath);
System.Reflection.MethodInfo method = assembly.EntryPoint;
return (T)appDomain.CreateInstanceFromAndUnwrap(assemblyPath, method.Name);
}
else
{
return (T)appDomain.CreateInstanceFromAndUnwrap(assemblyPath, className);
}
}
然后,在创建的实例上调用该方法,该方法在新的 appDomain 中执行:
void executeMethod(Type objecttype, string methodname, ref object instancedObject, object[] methodparams)
{
objecttype.InvokeMember(
methodname, System.Reflection.BindingFlags.InvokeMethod, null, instancedObject, methodparams);
}
你可以这样使用:
AppDomain newappdomain = getAppDomainForAssembly(filePath, "Loaded.exe.domain");
object loadedexe_object = getInstanceFromAppDomain(ref newappdomain,
filePath);
//If you know the method name to call...
executeMethod(loadedexe_object.GetType(), "methodname", ref loadedexe_object, null);
//or get entry point...
executeMethod(loadedexe_object.GetType(),
_asm_resolve(filePath).EntryPoint.Name, ref loadedexe_object, null);
对于第二个问题,您可以使用 NamedPipes、Remoting、WCF... 您需要在同一台机器上实现进程间通信。查看 MSDN 文档,使用 WCF 覆盖此场景的代码示例
http://msdn.microsoft.com/en-us/library/system.servicemodel.netnamedpipebinding.aspx
请参阅 CodeProject 上的此示例,通过 Remoting 使用 Remoting
进程间通信