Skip to content

Setting up a OWIN WebApi application

Mo Valipour edited this page Jun 21, 2016 · 8 revisions

This chapter explains a new feature from the release 3.2.1.

(FYI - You will need Version 3.2.4 or newer, otherwise you will get a Ninject.ActivationException regarding HttpConfiguration. See: stackoverflow thread for more details.)

This chapter explains how to setup an application in case you want to use the OWIN (Open Web Interface for .NET) interface to be able to move your application between OWIN supporting hosts without making code changes.

First you have to add a reference to Ninject.Web.Common.OwinHost and Ninject.Web.WebApi.OwinHost either by adding the reference manually or installing the corresponding NuGet Package.

Then you can initialize the Ninject middleware with the extension method UseNinjectMiddleware and register the WebApi through Ninject with the extension method UseNinjectWebApi. The call to app.UseWebApi(config) should be replaced with app.UseNinjectWebApi(config). start the WebApi you have to pass a Configuration object. This configuration is specific to the WebApi technology. Please read the documentation for this technologies to get more informations about how to configure a WebApi service.

public void Configuration(IAppBuilder app)
{
    var webApiConfiguration = new HttpConfiguration();
    webApiConfiguration.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "{controller}/{id}",
        defaults: new { id = RouteParameter.Optional, controller = "values" });

    app.UseNinjectMiddleware(CreateKernel).UseNinjectWebApi(webApiConfiguration);
}

private static StandardKernel CreateKernel()
{
    var kernel = new StandardKernel();
    kernel.Load(Assembly.GetExecutingAssembly());
    return kernel;
}