Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webapi 2 controllers on 2 projects

I have a webapi2 C# projects on which I have all the controllers in a controllers folder. I now have some functionality that I want to add but I want to put it on a different visual studio project that will have its own controllers (and models and views) folder. Is this possible so that I can create some kind of module that will be loaded by webapi2?

like image 326
tix3 Avatar asked Feb 02 '17 19:02

tix3


1 Answers

Web Api relies on the IHttpControllerSelector for choosing the api controller for handling a request, of which has a default implementation which relies on IAssembliesResolver for resolving the assemblies to search for the api controllers.

In the least minimum change, you can replace this assembly resolver with a custom implementation which will load other libraries for you.

A very naive example might look like the following:

public class CustomAssemblyResolver : IAssembliesResolver
{
    public List<string> PluginNames { get; set; }

    public CustomAssemblyResolver()
    {
        PluginNames = new List<string>();

        //Add the custom libraries here
        PluginNames.Add("Your_Second_Library");
    }

    public ICollection<Assembly> GetAssemblies()
    {
        var asms = AppDomain.CurrentDomain.GetAssemblies().ToList();
        foreach (var name in PluginNames)
        {

            var asmPath = System.IO.Path.Combine(HostingEnvironment.MapPath("~/"), name + ".dll");
            try
            {
                var asm= System.Reflection.Assembly.LoadFrom(asmPath);
                if(!asms.Contains(asm))
                    asms.Add(asm);
            }
            catch (Exception)
            {

            }
        }
        return asms;
    }
}

You can then replace the default resolver with this code

config.Services.Replace(typeof(IAssembliesResolver), new CustomAssemblyResolver());

inside your Register method of WebApiConfig class.

Then, copy all your additional libraries with controller classes to the bin directory and you are done.

If you need even further customization for controller selection, you can go for custom implementation of IHttpControllerSelector and replace the existing implementation in a similar fashion.

like image 195
Mat J Avatar answered Oct 16 '22 08:10

Mat J