Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically load assemblies in ASP.NET 5

I used to have some code which scanned the bin directory of my application for assemblies which weren't loaded in the AppDomain yet and loaded them. It basically looked like:

foreach (var assemblyPath in Directory.GetFiles("path\to\bin", "*.dll"))
{
    var inspected = Assembly.ReflectionOnlyLoadFrom(assemblyPath);
    Assembly.Load(inspected.GetName());
}

I skipped the try/catch clauses, etc for brevity.

This allowed me to drop assemblies in the bin folder at run-time with implementations for certain interfaces and let the IoC container pick them up automatically. Now with the new Roslyn magic, there are no physical DLL's anymore when debugging. Is there any way to retrieve assembly names, project names or dependency names (in project.json) dynamically.

I guess I have to implement something like this example in the Entropy repo, but I don't know how to implement it for my scenario.

like image 717
Henk Mollema Avatar asked Apr 02 '15 19:04

Henk Mollema


2 Answers

You can use the IAssemblyLoadContextAccessor interface to load ASP.NET 5 class library (.xproj) projects dynamically. The following example code works with Beta 4:

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        var assemblyLoadContextAccessor = app.ApplicationServices.GetService<IAssemblyLoadContextAccessor>();
        var loadContext = assemblyLoadContextAccessor.Default;
        var loadedAssembly = loadContext.Load("NameOfYourLibrary");
    }
}
like image 193
Jonas Lundgren Avatar answered Sep 20 '22 01:09

Jonas Lundgren


What you are looking for is ILibraryManager implementation which provides access to the complete graph of dependencies for the application. This is already flowed through the ASP.NET 5 DI system. So, you can reach out to it from there.

Sample usage can be found inside RoslynCompilationService.

like image 30
tugberk Avatar answered Sep 18 '22 01:09

tugberk