在Web API 2中将Ninject依赖项注入WebApiConfig

时间:2014-11-25 13:33:35

标签: ninject asp.net-web-api2

是否可以使用Ninject将依赖项注入WebApiConfig类?

这是我的WebApiConfig类。

        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                // Web API routes
                config.MapHttpAttributeRoutes();

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

                config.Services.Replace(typeof(IExceptionHandler), new ErrorHandlerMessageHandler(*NEEDS DEPENDENCY*));
            }
        }

这是我的NinjectHttpApplication声明

 public class WebApiApplication : NinjectHttpApplication
    {
        protected override void OnApplicationStarted()
        {
            base.OnApplicationStarted();
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }

        protected override IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            RegisterServices(kernel);

            GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
            return kernel;
        }

        private void RegisterServices(IKernel kernel)
        {
            //bindings
        }
    }

1 个答案:

答案 0 :(得分:3)

最后,我没有必要这样做,但我已经创建了一篇关于如何执行此操作的博文here