通常我们经常添加 dll 的引用,然后访问该 dll 中的类并创建该类的实例。现在我在我的项目中包含了一个 dll 文件作为嵌入资源。现在我的问题是,我如何访问类并创建该 dll 中包含为嵌入资源的类的实例。我搜索谷歌并找到stackoverflow链接,例如将一个dll作为嵌入式资源嵌入另一个dll中,然后从我的代码中调用它
我在那里找到的用于访问 dll 的指令,该指令包含在嵌入式资源中,例如
将第三方程序集作为资源嵌入后,添加代码以在应用程序启动期间订阅当前域的 AppDomain.AssemblyResolve 事件。只要 CLR 的 Fusion 子系统未能根据有效的探测(策略)定位程序集,就会触发此事件。在 AppDomain.AssemblyResolve 的事件处理程序中,使用 Assembly.GetManifestResourceStream 加载资源并将其内容作为字节数组提供给相应的 Assembly.Load 重载。下面是一个这样的实现在 C# 中的样子:
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
var resName = args.Name + ".dll";
var thisAssembly = Assembly.GetExecutingAssembly();
using (var input = thisAssembly.GetManifestResourceStream(resName))
{
return input != null
? Assembly.Load(StreamToBytes(input))
: null;
}
};
其中 StreamToBytes 可以定义为:
static byte[] StreamToBytes(Stream input)
{
var capacity = input.CanSeek ? (int) input.Length : 0;
using (var output = new MemoryStream(capacity))
{
int readLength;
var buffer = new byte[4096];
do
{
readLength = input.Read(buffer, 0, buffer.Length);
output.Write(buffer, 0, readLength);
}
while (readLength != 0);
return output.ToArray();
}
}
有几件事我不清楚。那个人说
添加代码以在应用程序启动期间订阅当前域的 AppDomain.AssemblyResolve 事件。只要 CLR 的 Fusion 子系统未能根据有效的探测(策略)定位程序集,就会触发此事件。
什么是 CLR 的 Fusion 子系统失败?这是什么意思?当 AssemblyResolve 事件触发时。我需要将此代码放在我的 program.cs 文件中吗?
Assembly.Load() 只会将程序集加载到内存中,但他们没有显示如何在该 dll 中创建类的实例?
请详细讨论我的兴趣点。谢谢