Injecting Ninject dependencies into WebApiConfig in Web API 2
Asked Answered
D

1

7

is it possible to inject dependencies into the WebApiConfig class using Ninject?

This is my WebApiConfig class.

        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*));
            }
        }

And this is my NinjectHttpApplication declaration

 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
        }
    }
Debrahdebrecen answered 25/11, 2014 at 13:33 Comment(0)
D
3

In the end I didn't have to do this but I have created a blog post on how to do this here

Debrahdebrecen answered 27/11, 2014 at 14:59 Comment(4)
thanks this post helped me, but I think some folks will already have this NinjectWebCommon class if they're adding WebAPI to an existing MVC project. I found that the following line was all I needed to add: GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(_kernel); after the RegisterServices(_kernel) call in the CreateKernel method. Note that this is the NinjectDependencyResolver from the Ninject.Web.WebApi namespace (may have to download separate NuGet package). Thanks!Sergent
I'm still trying to figure out how to do this. My NinjectWebCommon class already contains that line, however even I have one property decorated with the [Inject] attribute, the dependency is not being injected. Any thoughts?Steed
Have you moved your blog? Seems it's not available anymore.Steed
Updated my blog link for you @GonzaloMéndezDebrahdebrecen

© 2022 - 2024 — McMap. All rights reserved.