Search code examples
c#ninject

c# Ninject - Unbinding and releasing


I am using ninject for with the following code to bind and load the dependencies:

kernel.Bind(x =>
   x.FromAssembliesInPath(folder)
      .SelectAllClasses()
      .InheritedFrom<ISample>()
      .BindAllInterfaces()
      .Configure(binding => binding.InSingletonScope()));

var samples = kernel.GetAll<ISample>().ToList();

This works fine, and the dependencies are loaded successfullly.

I then have a separate routine to unload the dependencies, and wipe them out completely (delete the files off disk). Here is the code for that:

foreach (var s in samples)
{
    s.Dispose();   // ISample Implements IDisposable
}

kernel.Unbind<ISample>();
samples.Clear();
samples = null;

// Delete the folder which contains the ISample assemblies
Directory.Delete(folder, true);

The Directory.Delete() causes an UnauthorizedAccessException (Access to the path is denied.)

I must be missing a step that fully releases the dynamically loaded assemblies. I need help to identify what that step is, and what additional code is required to fully release the referenced assemblies so that they can be safely removed from disk.


Solution

  • What you want is not a limitation of Ninject, but a limitation of .NET. You can't unload assemblies from an AppDomain. The AppDomain will always keep the loaded assemblies referenced, and you can't delete the files from disk until the AppDomain is unloaded.

    So what you should do is spin up a second AppDomain from within the main app and load the assemblies from there. When you're done, you can unload the AppDomain from the main domain and after that you can delete the files.