Using Simple Injector with ASP.NET MVC 5

While ASP.NET Core has built-in capabilities for dependency injection, when attempting to accomplish this in MVC 5 one may come across a strange error:

No parameterless constructor defined for this object.

At a glance this is not entirely helpful. Adding a parameterless constructor is not a viable solution when you need to inject an interface. A third party library is still the best option for accomplishing this in MVC 5. This is a matter of preference, but for my needs Simple Injector continually stands out as one of the fastest options. It’s also lightweight and easy to install. Here is an example service for the HomeController:

private readonly IMyService myService;

public HomeController(IMyService myService)
{
     this.myService = myService;
}

public ActionResult Index()
{
     var model = this.myService.GetItems();

     return this.View(model);
}

Just add the SimpleInjector.Integration.Web.Mvc NuGet package to your solution and a bit of configuration:

protected void Application_Start()
{
     ...

     // 1. Create a new Simple Injector container
     var container = new Container();

     // 2. Configure the container (register)
     container.Register<IMyRepository, MyRepository>(Lifestyle.Transient);
     container.Register<IMyService, MyService>(Lifestyle.Transient);

     // 3. Optionally verify the container's configuration.
     container.Verify();

     // 4. Register the container.
     DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}

Simple Injector will take care of the rest.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s