How to use Ninject bootstrapper in WebApi OwinHost Startup?

江枫思渺然 提交于 2019-12-02 19:13:56
olif

Add the following nuget-packages to your application:

  1. Install-Package Microsoft.AspNet.WebApi.Owin
  2. Install-Package Ninject

If you are using web api version 5.0.0.0 you also need to download the Ninject Resolver class from the repo to avoid compatability issues.

Create a static method that returns a Kernel object

public static class NinjectConfig
{
    public static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        //Create the bindings
        kernel.Bind<IProductsRepository>().To<ProductRepository>();
        return kernel;
    }
}

Then you can use ninject in your startup class

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();
        config.DependencyResolver = new NinjectResolver(NinjectConfig.CreateKernel());

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

        app.UseWebApi(config);
    }
}

Create the kernel manually and then make UseNinjectMiddleware use the same one instead of creating another.

public void Configuration(IAppBuilder app)
{
  var kernel = CreateKernel()

  var config = new HttpConfiguration();
  config.MapHttpAttributeRoutes();

  // USE kernel here

  app.UseNinjectMiddleware(() => kernel);
  app.UseNinjectWebApi(config);
}

In addition to Olif's post:

  1. install-package ninject.extensions.conventions

  2. In your startup class add: using Ninject.Extensions.Conventions;

  3. Instead of manually binding:

 public static IKernel CreateKernel()
     {
         var kernel = new StandardKernel();
         //Create the bindings
         kernel.Bind<IProductsRepository>().To ProductRepository ();
         return kernel;
     }

You can now do:

kernel.Bind(x =>
                {
                    x.FromThisAssembly()
                    .SelectAllClasses()
                    .BindDefaultInterface();
                });

This will look through your assembly, and do the binding automatically.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!