Search code examples
asp.net-web-api2katana

Web api code in separate dll for Owin/Katana selfhosting scenario


I got a working web-api 2 application that was developed using the defaults. It resides in app.dll.

Now i try to add a new console app project that would self-host this application using Katana. I added app.dll as reference. The problem is, that when i run this self hosted app and try to send a simple get request to the api, it doesn't find any controllers. I got the following error message: No type was found that matches the controller named 'MyController'.

Now, I try to force controllers to be found using this way. But apparently, I'm doing something wrong as the code in GetAssemblies() never gets invoked.

The code sample is below:

public class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        HttpConfiguration config = new HttpConfiguration();
        config.Services.Replace(typeof (IAssembliesResolver), new AssembliesResolver());
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );app
        appBuilder.UseWebApi(config);
    } 
}

public class AssembliesResolver : DefaultAssembliesResolver
{
    public override ICollection<Assembly> GetAssemblies()
    {
        ICollection<Assembly> baseAssemblies = base.GetAssemblies();
        List<Assembly> assemblies = new List<Assembly>(baseAssemblies);
        var controllersAssembly = Assembly.LoadFrom(@"app.dll");
        baseAssemblies.Add(controllersAssembly);
        return assemblies;
    }
}

Solution

  • Try creating a new AssemblyResolver class in the actual project with the ApiControllers. Then using this for getting the assembly.

       public override ICollection<Assembly> GetAssemblies()
        {
            return new List<Assembly>
            {
                typeof (AssembliesResolver).Assembly
            };
        }
    

    This is just assuming you only have the ApiControllers in that single DLL.