Loading Web API Controllers from other Libraries when Self Hosting Web API

When Self Hosting Web API, we have to create controllers on the same project, otherwise it does not detect the libraries even if we reference the Web API project where we have all the controllers and classes defined.

For example, if we have a Web API project which was hosted over IIS earlier and we decided to Self Host it on a windows service project or a console application; we have to copy-paste or drag/drop the classes from the Web API project to Self Host Web API project and also have to change its namespace so it could be searchable by the Web API framework. But what if we have a centralized project where we have all the controllers in place and we want Self Host Web API project to load all the controllers from there.

In order to overcome this scenario we can create a custom assembly resolver let say SelfHostAssemblyResolver and replace the default one to this. SelfHostAssemblyResolver implements IAssemblyResolver interface and then implements the GetAssemblies method that loads the assemblies from particular path.

So first, create a custom assembly resolver


In the below code, where you are initializing the Self Host Web API, replace the default assembly resolver with your custom assembly resolver using HttpSelfHostConfiguration object.


In the above code snippet, DemoWebApi.dll is the main Web API project I was using initially, that had used the default Web API hosting on IIS.

Happy coding!

4 thoughts on “Loading Web API Controllers from other Libraries when Self Hosting Web API

  1. Hi,

    I tried your code but it does not work for me. Here is my code:

    //—————–ProcessingServiceApp.exe———————————————————-
    class ProcessingServiceApp
    {
    static readonly Uri _baseAddress = new Uri(“http://localhost:9999/”);

    static void Main(string[] args)
    {

    // Set up server configuration
    HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress);

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

    config.Routes.MapHttpRoute(
    name: “DefaultApi”,
    routeTemplate: “api/{controller}/{id}”,
    defaults: new { id = RouteParameter.Optional }
    );

    // Create server
    var server = new HttpSelfHostServer(config);
    // Start listening
    server.OpenAsync().Wait();
    Console.WriteLine(“Web API Self hosted on ” + _baseAddress + ” Hit ENTER to exit…”);
    Console.ReadLine();
    server.CloseAsync().Wait();
    }
    }

    public class DynamicAssemblyResolver : DefaultAssembliesResolver
    {
    public override ICollection GetAssemblies()
    {
    try
    {
    ICollection baseAssemblies = base.GetAssemblies();
    List assemblies = new List(baseAssemblies);
    var controllersAssembly = Assembly.LoadFrom(“Controller.dll”);
    if (controllersAssembly != null)
    {
    assemblies.Add(controllersAssembly);
    }

    return assemblies;
    }
    catch (Exception ex)
    {
    throw ex;
    }
    }
    }

    //——————————————-Controller.dll————————————————-

    public class Car
    {
    public String Brand { get; set; }
    public String Modell { get; set; }
    public int HorsePower { get; set; }
    }

    public class MyCarsController : ApiController
    {
    Car[] MyCars = new Car[]
    {
    new Car{Brand = “BMW”, Modell=”3er”, HorsePower=184},
    new Car{Brand = “Audi”, Modell=”A4″, HorsePower=170},
    new Car{Brand = “Ford”, Modell=”Focus”, HorsePower=90},
    };

    public IEnumerable Get()
    {
    return MyCars;
    }

    public Car Get(String brand)
    {
    var car = MyCars.FirstOrDefault((p) => p.Brand == brand);
    if (car == null)
    {
    throw new HttpResponseException(HttpStatusCode.NotFound);
    }
    return car;
    }

    public IEnumerable GetCarsByHorsePower(int ps)
    {
    return MyCars.Where(p => p.HorsePower == ps);
    }

    public IEnumerable GetAllCarsWithLowerHorsePower(int minPs)
    {
    return MyCars.Where(p => p.HorsePower < minPs);
    }
    }

    I tried to use http://localhost:9999/api/MyCars with forefox but I got following error:

    No HTTP resource was found that matches the request URI 'http://localhost:9999/api/MyCars&#039;.

    In Debugger, I saw, that GetAssemblies() was called and no exception was thown. What is wrong?

    If I make a copy of the MyCarsController and Car-class and put it into the ProcessingServiceApp-Project in VisualStudio, all works fine.

    Thanks and Regards
    Daniel

      • I created a test project for you and its working with the same code mentioned above, One thing you have to check that the Assemblies version referenced in Self host application should match with the assemblies referenced in Web API Project. In my case the version of System.Web.Http is 5.0.0.0 in both the projects. Please check and provide me your email where I can send you that project.

Leave a comment