Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting Ninject dependencies into WebApiConfig in Web API 2

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
        }
    }
like image 413
Mark Walsh Avatar asked Nov 25 '14 13:11

Mark Walsh


1 Answers

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

like image 114
Mark Walsh Avatar answered Jan 03 '23 13:01

Mark Walsh