如何释放使用反射加载的 DLL?

How to release a DLL that was loaded with Reflection?

String dlls = ConfigurationManager.AppSettings["ApiFolder"];
FileInfo[] files = new DirectoryInfo(dlls).GetFiles("*.dll");
foreach (FileInfo file in files) {
    if (!LoadedApis.ContainsKey(file.Name)) {
        Assembly ass = Assembly.LoadFrom(dlls + file.Name);
        foreach (Type t in ass.GetTypes()) {
            if (t.GetTypeInfo().FindInterfaces((x, y) => true, null).Contains(typeof(IApi))) {
                IApi api = (IApi)ass.CreateInstance(t.FullName);
                LoadedApis.Add(file.Name, api);
            }
        }
    }
}

我正在使用上面的代码将具有特定接口的所有 DLL 从文件夹加载到字典中,以便稍后访问它们。我正在开发一个插件系统,你所要做的就是放入一个 DLL,它将被加载和使用。

它运行良好,但有一个用例我想说明,但我目前不知道该怎么做。我想允许删除或更新 DLL。

是否可以释放已经反射加载的DLL,以便删除或覆盖?我想我必须进行一些互操作调用,但我不知道要进行哪些调用。

或者,另一种方法,我可以将 DLL 加载到内存中,这样我就永远不会锁定文件吗?

There is no way to unload an individual assembly without unloading all of the application domains that contain it. Use the Unload method from AppDomain to unload the application domains. For more information, see How to: Unload an Application Domain.

来源:https://msdn.microsoft.com/en-us/library/ms173101.aspx