BuildManager.AddReferencedAssembly in NetCORE

Viewed 167

I have 2 web api project with net core. 1.- Base web api. 2.- Contact web api.

I can load contact web api dynamically from base web api. but entities and layers assemblies are not loaded. For contacts web api to work, I must add the reference manually entities and layers assemblies in base web api. In NET Framework I use BuildManager.AddReferencedAssembly, but in net core don't exist. How can I add a dynamic reference with net core?. Thnaks.

1 Answers

I was working at MVC that project was on plugin system. In this project, I also was using "BuildManager.AddReferencedAssembly" method to add an assembly's reference. Unfortunately, this method can use only in framework 4.x.

After some research I found a solution to over with this problem on this address:

https://github.com/simplcommerce/SimplCommerce

You can analyse this project to improve your solution. (I assume you are working on a plugin system)

But, if you need just a method to replace "BuildManager.AddReferencedAssembly" method, you can use this:

static void AddApplicationPart(IMvcBuilder mvcBuilder, Assembly assembly)
{
    var partFactory = ApplicationPartFactory.GetApplicationPartFactory(assembly);
    foreach (var part in partFactory.GetApplicationParts(assembly))
    {
        mvcBuilder.PartManager.ApplicationParts.Add(part);
    }

    var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(assembly, throwOnError: false);
    foreach (var relatedAssembly in relatedAssemblies)
    {
       partFactory = ApplicationPartFactory.GetApplicationPartFactory(relatedAssembly);
       foreach (var part in partFactory.GetApplicationParts(relatedAssembly))
       {
           mvcBuilder.PartManager.ApplicationParts.Add(part);
       }
    }
}

To use this method, you need IMvcBuilder. You can get it from a code like this:

IMvcBuilder  _mvcBuilder = services.AddMvc();

"services" variable must be a type derived from IServiceCollection. Simply, you can find it in ConfigureServices method in StartUp class.

And as final word, I can say this with complacency, I have tested and it works.

Related