2
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);
            }
        }
    }
}

I'm using the above code to load all DLLs that have a particular interface from a folder into a dictionary where I can access them later. I'm working on a plug in system where all you have to do is drop in a DLL and it will be loaded and used.

It's working great but there's one use case I want to account for that I currently don't know how to do. I want to allow for the DLLs to be removed or updated.

Is it possible to release a DLL that has been loaded with reflection so that it can be deleted or overwritten? I imagine I'll have to make a few interop calls but I don't know which ones to make.

Or, a different approach, can I load the DLL into memory so I never have a lock on the file to begin with?

Corey Ogburn
  • 24,072
  • 31
  • 113
  • 188

1 Answers1

2

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.

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

Erti-Chris Eelmaa
  • 25,338
  • 6
  • 61
  • 78