[英]Load Assembly into AppDomain
如果我用
Assembly assembly = Assembly.LoadFrom(file);
后来尝试使用该文件,我收到异常说明该文件正在使用中。
我需要将其加载到新的appdomain上。
我似乎只发现了如何在Assembly中创建实例的示例, 有没有办法加载整个Assembly 。
我需要的是:
(1) load the assembly into a new AppDomain from a file .
(2) extract an embedded resource (xml file) from the Dll .
(3) extract a type of class which implements an interface (which i know the interface type) .
(4) unload the entire appdomain in order to free the file .
2-4不是问题
我似乎只是找不到如何将Assembly加载到新的AppDomin中 ,仅是create实例的示例,这使我对Dll中的with有了该类的实例。
我需要整个东西。
像这个问题:创建实例的另一个例子。
最基本的多域方案是
static void Main()
{
AppDomain newDomain = AppDomain.CreateDomain("New Domain");
newDomain.ExecuteAssembly("file.exe");
AppDomain.Unload(newDomain);
}
在单独的域上调用ExecuteAssembly
很方便,但不能与域本身进行交互。 它还要求目标程序集是可执行文件,并将调用程序强制到单个入口点。 为了增加灵活性,您还可以将字符串或args传递给.exe。
我希望这有帮助。
扩展:然后尝试以下类似的操作
AppDomainSetup setup = new AppDomainSetup();
setup.AppDomainInitializer = new AppDomainInitializer(ConfigureAppDomain);
setup.AppDomainInitializerArguments = new string[] { unknownAppPath };
AppDomain testDomain = AppDomain.CreateDomain("test", AppDomain.CurrentDomain.Evidence, setup);
AppDomain.Unload(testDomain);
File.Delete(unknownAppPath);
可以按以下方式初始化AppDomain
public static void ConfigureAppDomain(string[] args)
{
string unknownAppPath = args[0];
AppDomain.CurrentDomain.DoCallBack(delegate()
{
//check that the new assembly is signed with the same public key
Assembly unknownAsm = AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(unknownAppPath));
//get the new assembly public key
byte[] unknownKeyBytes = unknownAsm.GetName().GetPublicKey();
string unknownKeyStr = BitConverter.ToString(unknownKeyBytes);
//get the current public key
Assembly asm = Assembly.GetExecutingAssembly();
AssemblyName aname = asm.GetName();
byte[] pubKey = aname.GetPublicKey();
string hexKeyStr = BitConverter.ToString(pubKey);
if (hexKeyStr == unknownKeyStr)
{
//keys match so execute a method
Type classType = unknownAsm.GetType("namespace.classname");
classType.InvokeMember("MethodNameToInvoke", BindingFlags.InvokeMethod, null, null, null);
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.