【问题标题】:Injecting Ninject dependencies into WebApiConfig in Web API 2在 Web API 2 中将 Ninject 依赖项注入 WebApiConfig
【发布时间】:2014-11-25 13:33:35
【问题描述】:

是否可以使用 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
        }
    }

【问题讨论】:

    标签: ninject asp.net-web-api2


    【解决方案1】:

    最后我不必这样做,但我创建了一篇关于如何做到这一点的博客文章here

    【讨论】:

    • 感谢这篇文章对我的帮助,但我认为如果将 WebAPI 添加到现有 MVC 项目中,有些人已经拥有这个 NinjectWebCommon 类。我发现我只需要添加以下行:GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(_kernel);RegisterServices(_kernel) 调用之后CreateKernel 方法。请注意,这是来自 Ninject.Web.WebApi 命名空间的 NinjectDependencyResolver(可能需要下载单独的 NuGet 包)。谢谢!
    • 我仍在试图弄清楚如何做到这一点。我的 NinjectWebCommon 类已经包含该行,但是即使我有一个用 [Inject] 属性装饰的属性,也没有注入依赖项。有什么想法吗?
    • 您的博客移动了吗?好像没有了。
    • 为你更新了我的博客链接@GonzaloMéndez
    猜你喜欢
    • 2018-10-19
    • 2018-03-24
    • 2016-04-28
    • 2011-04-06
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    • 2013-12-04
    • 2018-12-31
    相关资源
    最近更新 更多