Dynamically load assemblies in ASP.NET 5

爱⌒轻易说出口 提交于 2019-12-03 08:54:05

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.

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

I solved this issue partly using the ILibraryManager as suggested by @tugberk. I changed the approach a bit which dropped the need of scanning the bin folder for new assemblies. I just want all the loaded assemblies in the current AppDomain.

I injected an instance of the ILibraryManager interface in my type finder class and used the GetReferencingLibraries() method with the name of the core assembly, which is referenced by all the other assemblies in the application.

A sample implementation can be found here, where this is the important part:

public IEnumerable<Assembly> GetLoadedAssemblies()
{
    return _libraryManager.GetReferencingLibraries(_coreAssemblyName.Name)
                          .SelectMany(info => info.Assemblies)
                          .Select(info => Assembly.Load(new AssemblyName(info.Name)));
}

For .net core users, here is my code for loading assemblies from a specific path. I had to use directives, as it's slightly different for .Net Framework and .Net Core.

In your class header you'll need to declare the using something similar to:

#if NET46
#else
    using System.Runtime.Loader;
#endif

And in your function something similar to the following:

string assemblyPath = "c:\temp\assmebly.dll";

#if NET46
                Assembly assembly = Assembly.LoadFrom(assemblyPath);
#else
                AssemblyLoadContext context = AssemblyLoadContext.Default;
                Assembly assembly = context.LoadFromAssemblyPath(assemblyPath);
#endif
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!