【问题标题】:Using MEF in C# MVC, Assembly Loading some DLLs, how do I unload them?在 C# MVC 中使用 MEF,程序集加载一些 DLL,如何卸载它们?
【发布时间】:2017-09-04 07:39:41
【问题描述】:

抱歉,我不确定我是否正确地表达了这个问题,这是我的情况...使用 .NET 4.6 和 MEF。

我有一个核心网站,它在运行时检查模块文件夹中的 DLL 并将它们拉入组合容器/MEF 事物中,这让我可以在我的核心中使用第 3 方项目的视图/控制器。

为了允许强类型,我遵循this guide,它建议在 PreApplicationStartMethod 中制作 DLL 的卷影副本。

到目前为止一切正常,真的很棒。

当我停止调试或服务器重新编译时出现问题。 DLL 没有正确释放,所以我第二次收到拒绝访问错误。当我尝试将 DLL 复制到卷影复制文件夹中时会发生错误。

The process cannot access the file '....dll' because it is being used by another process.

我猜是 BuildManager.AddReferencedAssembly(assemblyDll) 将文件锁定在...但是否有可靠的方法在崩溃或启动时卸载程序集?

static PreApplicationInit()
    {
        PluginFolder = new DirectoryInfo(HostingEnvironment.MapPath("~/Modules"));
        ShadowCopyFolder = new DirectoryInfo(HostingEnvironment.MapPath("~/Modules/temp"));
    }
public static void Initialize()
    {
        Directory.CreateDirectory(ShadowCopyFolder.FullName);

        //clear out plugins)
        foreach (var f in ShadowCopyFolder.GetFiles("*.dll", SearchOption.AllDirectories))
        {
            f.Delete(); // -- Breaks here
        }

        //shadow copy files
        foreach (var plug in PluginFolder.GetFiles("*.dll", SearchOption.AllDirectories))
        {
            var di = Directory.CreateDirectory(Path.Combine(ShadowCopyFolder.FullName, plug.Directory.Name));
            File.Copy(plug.FullName, Path.Combine(di.FullName, plug.Name), true); // -- Or if Delete is Try Caught, Breaks here
        }

        foreach (var a in
            ShadowCopyFolder
            .GetFiles("*.dll", SearchOption.AllDirectories)
            .Select(x => AssemblyName.GetAssemblyName(x.FullName))
            .Select(x => Assembly.Load(x.FullName)))
        {
            BuildManager.AddReferencedAssembly(a);
        }

    }

【问题讨论】:

    标签: c# .net dll mef


    【解决方案1】:

    可能有很多可能的原因,但我认为主要原因是,当您重新编译之前编译中的一些 dll 时,它仍在进行中,并且在整个过程完成之前它不会让您访问(在一个术语,它将有一个锁)。 如果要重新编译,请尝试更改文件夹。它应该工作。

    【讨论】:

    • 嗯。我没有考虑第二个文件夹...这不会产生两个 DLL 加载相同名称和方法等的问题吗?
    • 只有目标文件夹是一个才会报错
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多