Search code examples
ninject-2asp.net-web-apininject-extensions

ASP.NET Web API (Self Host) + Ninject - Default Bindings


I'm converting a project from WCF Web API to ASP.NET Web API - thanks MS :(

Self Hosting POC code:

    static void Main(string[] args)
    {
        var kernel = new StandardKernel();

        const string baseAddress = "http://localhost:8080";
        var config = new HttpSelfHostConfiguration(baseAddress);
        config.ServiceResolver.SetResolver(new NinjectServiceLocator(kernel));

        config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new {id = RouteParameter.Optional});

        var server = new HttpSelfHostServer(config);
        server.OpenAsync().Wait();
        Console.WriteLine("The server is running....");
        Console.ReadLine();
    }

I'm registering Ninject as the dependency resolver. To accomplish this, I am using the CommonServiceLocator.NinjectAdapter to register it:

config.ServiceResolver.SetResolver(new NinjectServiceLocator(kernel));

This seems to work as far as I can tell although it feels a little dirty using SetResolver(object).

The problem I have now is when I try to run it there are a lot of bindings that are no longer registered (i.e. IHttpContollerFactory, ILogger, etc.).

Do I have to go through one-by-one and re-register all of the "default" dependencies? It seems odd that defaults are registered with the default dependency resolver but I can't see a quick way to re-register the defaults when a new dependency resolver is set. For something like the ILogger, I can't even seem to gain access to the default System.Web.Http.Common.Logging.DiagnosticLogger to make the binding.

Am I missing something?


Solution

  • You don't have to re-register the default services. If you return null the framework will default back to it's internal DI container. Also, in the latest bits it will only ask once.