我正在开发一个使用反射来加载插件的.NET应用程序。我的插件是C#类库。问题是我的一些插件引用了传统的Win32 DLL,而C#盲目地尝试加载依赖项,就好像它们是.NET DLL一样。
以下是我加载插件的方法:
string fileName = "plugin.dll";
Assembly.LoadFrom(fileName);
我收到System.BadImageFormatException
,其中包含以下消息:
Could not load file or assembly 'plugin.dll' or one of its dependencies.
The module was expected to contain an assembly manifest.
如何以编程方式加载引用Win32 DLL的程序集?
答案 0 :(得分:1)
如果你只需要dll中的某些功能,你可以这样做:
[DllImport("plugin.dll")]
public static extern void SomeFunction();
答案 1 :(得分:1)
您是否尝试过Assembly.LoadFile()?
请记住,LoadFile不会将文件加载到LoadFrom上下文中,也不会像LoadFrom方法那样使用加载路径解析依赖关系。在这种有限的情况下,LoadFile非常有用,因为LoadFrom不能用于加载具有相同标识但路径不同的程序集;它只会加载第一个这样的组件
答案 2 :(得分:1)
您需要以下内容:
foreach (string filePath in Directory.GetFiles(path, "*.DLL"))
{
try
{
_assemblies.Add(Assembly.LoadFile(filePath));
}
catch (FileNotFoundException)
{
// Attempted to load something with a missing dependency - ignore.
}
catch (BadImageFormatException)
{
// Attempted to load unmanaged assembly - ignore.
}
}
您仍然需要确保您的依赖项受管理或本机可用,并且不会意外加载本机DLL。对于托管程序集,可能需要更改app.config中的.net探测路径以确保找到它们:
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="modules"/>
</assemblyBinding>
</runtime>
理想情况下,您希望将插件放在一个单独的目录中,因为在您不感兴趣的许多程序集上调用LoadFile很慢,一旦您将程序集加载到AppDomain中,就无法卸载它。