【问题标题】:Loading and then Unloading DLL with dependency locks the DLL加载然后卸载具有依赖关系的 DLL 会锁定 DLL
【发布时间】:2019-09-26 08:39:47
【问题描述】:

动态加载具有依赖关系的 DLL 然后卸载它,仍然锁定 DLL,我无法删除/替换 dll。

作为编写插件应用程序的一部分,我动态加载 DLL(它具有依赖项,例如 Newtonsoft.Json),运行加载的程序集,然后卸载它。卸载后,我无法从磁盘中删除 DLL(直到我重新启动我的应用程序),但是,如果我使用没有依赖关系的 DLL,它可以正常工作,并且不会锁定文件。 该实现基于 .NET core 3 加载/卸载,取自: https://docs.microsoft.com/en-us/dotnet/standard/assembly/unloadability

我使用AssemblyLoadContext,它有一个解析器,例如:

class TestAssemblyLoadContext : AssemblyLoadContext
{
    private AssemblyDependencyResolver _resolver;

    public TestAssemblyLoadContext(string mainAssemblyToLoadPath) : base(isCollectible: true)
    {
        _resolver = new AssemblyDependencyResolver(mainAssemblyToLoadPath);
    }

    protected override Assembly Load(AssemblyName name)
    {
        string assemblyPath = _resolver.ResolveAssemblyToPath(name);
        if (assemblyPath != null)
        {
            return LoadFromAssemblyPath(assemblyPath);
        }

        return null;
    }
}

以及创建上下文的代码:

    [MethodImpl(MethodImplOptions.NoInlining)]
    public static void runCommands(string pluginPath, bool execute,out WeakReference alcWeakRef)
    {
        string pluginLocation = getPath(pluginPath);

        PluginLoadContext loadContext = new PluginLoadContext(pluginLocation);
        alcWeakRef = new WeakReference(loadContext, trackResurrection: true);

        Assembly pluginAssembly = loadContext.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(pluginLocation)));

        var commands = CreateCommands(pluginAssembly).ToList();


        if (execute) {
            Console.WriteLine("Commands: ");
            foreach (ICommand command in commands)
            {
                Console.WriteLine($"executing... {command.Execute()}");
            }
        }

        commands.Clear();
        loadContext.Unload();
    }

如果这是我做错的事情,我会徘徊,我已经尝试从流中加载文件,例如:

using (var fs = new FileStream(pluginLocation, FileMode.Open, FileAccess.Read))
{
    var pluginAssembly = loadContext.LoadFromStream(fs);
    ....
    ....
}

【问题讨论】:

  • 您对这个问题有任何更新吗?因为我也在为此寻找解决方案
  • @Justin99b 我回答了我自己的问题,这是给你和其他所有人的 :)

标签: c# .net .net-core dynamic-loading .net-core-3.0


【解决方案1】:

问题解决了,基本上在卸载 DLL 时,如果你有 Newtonsoft.Json 依赖项,你就不能这样做,因为它们有一个锁定文件的错误。

这是基于github issue我打开的回复

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多