【问题标题】:Why AssemblyResolver fire even when dll is loaded (manualy)?为什么即使(手动)加载了 dll,AssemblyResolver 也会触发?
【发布时间】:2015-08-24 09:06:18
【问题描述】:

我有 2 个项目的 C# 解决方案:

  1. DLLTest(控制台应用)
  2. BLib(库)

在 DLLTest 中,我设置了对 BLib 的引用并将 Copy Local 属性设置为 false。
编译解决方案。
将 BLib.dll 复制到“C:\BLib.dll”并运行应用程序。
在我的代码的第一步中,我从路径“C:\BLib.dll”加载程序集,然后从那里调用方法。在从 BLib 程序集调用方法时,触发 AssemblyResolver 并尝试加载我之前手动加载的程序集。

我可以对应用程序执行一些操作以知道该库已加载并且不再尝试加载它吗?
这是来自 BLib 项目的 BClass.cs 文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BLib
{
    public class BClass
    {
        public static void PrintName()
        {
            Console.WriteLine("BLib");
        }
    }
}

这是来自 DLLTest 项目的 Program.cs 文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace DLLTest
{
    class Program
    {
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
            Assembly.LoadFile(@"C:\BLib.dll");
            Console.WriteLine("Loaded assembles:");
            AppDomain.CurrentDomain.GetAssemblies().ToList()
                .ForEach(p => Console.WriteLine(p));
            Console.WriteLine("End list of assembles");
            try
            {
                PrintMessage();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadKey();
        }

        private static void PrintMessage()
        {
            BLib.BClass.PrintName();
        }

        private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            Console.WriteLine(args.Name);
            return null;
        }
    }
}

【问题讨论】:

    标签: c# .net dll .net-assembly


    【解决方案1】:

    我找到了类似的问题Why is AssemblyResolve called when Assembly is in CurrentDomain? 从那里回答我到Choosing a Binding Context 那里详细描述了所有内容(行既没有缺点)。

    我认为是这样,这是安全原因。

    【讨论】:

      猜你喜欢
      • 2021-10-07
      • 2015-03-04
      • 2020-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多