How to use Ninject bootstrapper in WebApi OwinHost Startup?

前端 未结 3 680
借酒劲吻你
借酒劲吻你 2021-02-01 20:52

I am migrating from IIS WebAPI to OwinHost. Utilizing the latest pre-release versions of nuget packages, I successfully used instructions here:

https://github.com/ninje

3条回答
  •  死守一世寂寞
    2021-02-01 21:20

    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().To();
            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);
        }
    }
    

提交回复
热议问题