1

通常我们经常添加 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 中创建类的实例?

请详细讨论我的兴趣点。谢谢

4

1 回答 1

1

什么是 CLR 的 Fusion 子系统出现故障?这是什么意思?

本文详细解释(尤其是Probing for the Bits (Fusion)部分):

当探测无法定位程序集时,它将触发 AppDomain.AssemblyResolve 事件,允许用户代码执行自己的自定义加载。如果所有其他方法都失败,则抛出 TypeLoadException(如果加载过程是由于对依赖程序集中的类型的引用而被调用)或 FileNotFoundException(如果手动调用加载过程)。


Assembly.Load() 只会将程序集加载到内存中,但他们没有显示如何在该 dll 中创建类的实例?

SO中的另一个问题解释了如何在动态加载的程序集中创建类型的实例。

于 2012-05-08T09:19:18.727 回答