【发布时间】:2018-11-08 08:39:20
【问题描述】:
我想在当前项目的单独解决方案中动态使用来自不同项目的类。我认为解决方案是将dll加载到我的项目中。我使用下面的代码来完成我的任务,并且成功了。
string dllPath = @"the path of my dll";
var DLL = Assembly.LoadFile(dllPath);
foreach (Type type in DLL.GetExportedTypes())
{
if (type.Name == "targetClassName")
{
var c = Activator.CreateInstance(type);
try
{
type.InvokeMember("myMethod", BindingFlags.InvokeMethod, null, c, new object[] { "Params" });
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
break;
}
}
但是,我现在的问题是我想卸载 dll,我不能这样做,因为在 Assembly 中没有卸载方法。我找到的解决方案是我必须使用 AppDomain 加载程序集,然后再卸载它。
现在这是我的主要问题。我不断收到FileNotFoundException。这是我的代码:
public class ProxyDomain : MarshalByRefObject
{
public Assembly GetAssembly(string assemblyPath)
{
try
{
return Assembly.LoadFrom(assemblyPath);
}
catch (Exception ex)
{
throw new InvalidOperationException(ex.Message);
}
}
}
private void BuildButton_Click(object sender, EventArgs e)
{
string dllPath = @"DllPath";
string dir = @"directory Path of the dll";
AppDomainSetup domaininfo = new AppDomainSetup();
domaininfo.ApplicationBase = System.Environment.CurrentDirectory;
Evidence adevidence = AppDomain.CurrentDomain.Evidence;
AppDomain domain = AppDomain.CreateDomain("MyDomain", adevidence, domaininfo);
Type Domtype = typeof(ProxyDomain);
var value = (ProxyDomain)domain.CreateInstanceAndUnwrap(
Domtype.Assembly.FullName,
Domtype.FullName);
var DLL = value.GetAssembly(dllPath);
// Then use the DLL object as before
}
最后一行出现以下异常Could not load file or assembly 'dll, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
我已经尝试了这个link 的解决方案,但没有什么对我有用...我一直遇到同样的异常。之后我想卸载域,但我无法解决加载 dll 的第一个问题。如何修复我的代码?
编辑
当我将预期的 dll 复制到项目的同一个 bin 文件夹中时,它可以工作。但是,我不想在我的项目中复制 dll。有没有办法从它的路径加载它而不将它复制到我的 bin 文件夹?
【问题讨论】:
-
注意:DLL一旦加载就无法卸载
-
是的,这就是为什么我需要使用AppDomain,所以我可以在完成后卸载它。
-
看起来你帮的太多了,你不想自己做 AppDomainSetup。使用 Environment.CurrentDirectory 非常麻烦,它是一个丑陋的全局变量,在 SO 问题中大约 100% 的时间其值设置错误。只需使用 CreateDomain(string) 重载。
-
你的意思是保持我相同的逻辑,但删除 AppDomainSetup 并只使用 CreateDomain(string)?我这样做了,但总是遇到同样的异常。
-
您可能必须从 AppDomain 卸载和删除才能卸载程序集。在blog.vcillusion.co.in/… 上尝试示例希望它有所帮助!
标签: c# assemblies appdomain