c# – 将DLL加载到单独的AppDomain中
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 将DLL加载到单独的AppDomain中,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2362字,纯文字阅读大概需要4分钟。
内容图文
![c# – 将DLL加载到单独的AppDomain中](/upload/InfoBanner/zyjiaocheng/821/5f4875c70ecd42e58654b19681084193.jpg)
我正在编写一个插件架构.我的插件dll位于运行插件管理器的子目录中.
我将插件加载到单独的AppDomain中,如下所示:
string subDir;//initialized to the path of the module's directory.
AppDomainSetup setup = new AppDomainSetup();
setup.PrivateBinPath = subDir;
setup.ApplicationBase = subDir;
AppDomain newDomain= AppDomain.CreateDomain(subDir, null, setup);
byte[] file = File.ReadAllBytes(dllPath);//dll path is a dll inside subDir
newDomain.Load(file);
然而. newDomain.Load返回当前域尝试加载的程序集.因为插件dll位于子目录中,所以当前域不能也不应该看到这些dll,并且当前域会抛出FileLoadException
“ex = {”无法加载文件或程序集……或其中一个依赖项.“
问题是,我们可以将程序集加载到单独的AppDomain中而不返回已加载的程序集吗?
我知道我可以在当前域中为AssemblyResolve事件添加一个处理程序并返回null,但我宁愿不去这条路线.
提前致谢.
解决方法:
你也可以使用DoCallBack – 这是我在SO上阅读了很多关于它的东西.这将创建一个appdomain,检查程序集是否具有相同的签名公钥,加载程序集,执行静态方法,卸载appdomain,然后删除dll.
static void Main(string[] args)
{
string unknownAppPath = @"path-to-your-dll";
Console.WriteLine("Testing");
try
{
AppDomainSetup setup = new AppDomainSetup();
setup.AppDomainInitializer = new AppDomainInitializer(TestAppDomain);
setup.AppDomainInitializerArguments = new string[] { unknownAppPath };
AppDomain testDomain = AppDomain.CreateDomain("test", AppDomain.CurrentDomain.Evidence, setup);
AppDomain.Unload(testDomain);
File.Delete(unknownAppPath);
}
catch (Exception x)
{
Console.WriteLine(x.Message);
}
Console.ReadKey();
}
public static void TestAppDomain(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("method-you-want-to-invoke", BindingFlags.InvokeMethod, null, null, null);
}
});
}
内容总结
以上是互联网集市为您收集整理的c# – 将DLL加载到单独的AppDomain中全部内容,希望文章能够帮你解决c# – 将DLL加载到单独的AppDomain中所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。