Simple Injector MVC and Web API

So you want to have both WebAPI and MVC controllers in the same project. You add in the route configurations and the WebAPI controllers and come to run the project however you get an exception like this..

ExceptionMessage=Type 'MyProject.Web.Controllers.api.ProductController' does not have a default constructor

This seems odd, as you’re passing objects into the controller which you have previously configured the dependency injection for. The issue is that MVC and WebAPI have separate dependency resolvers and therefore no object is injected into the WebAPI controller at runtime.

The solution to this is to register a simple inject dependency resolver to both dependency resolvers.

You need to make sure that you have referenced the Simple Injector WebAPI libraries. (These can be added through NuGet)


Then add the following line within your `Global.asax.cs` when you set the MVC dependency resolver.

GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);

Your `Global.asax.cs` should now look something like this..

protected void Application_Start()

        var container = new Container();

        container.Register<INonGenericDBService, NonGenericDBService>();
        container.Register<IUserRepository, UserRepository>();           

        GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
        DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));




comments powered by Disqus