Simple Injector and ASP.NET MVC 5

Using ASP .NET MVC 5 still has the classical web application project structure (compared against the new MVC 6), and dependency injection (DI) is quite straightforward using a third party library. And to make this process even simpler, I decided to try out Simple Injector. It’s a very simple and fast DI .NET library.

Simple Injector logo

Let’s go with an extremely simple example just to illustrate how to start working with Simple Injector.

I’ve created an empty web application project in Visual Studio 2015 using .NET v4.6.1, and after adding my Home controller got MVC application scaffold. Then removed  everything I could to keep the application as simple as possible yet fully working, so it would have an emphasis on Simple Injector DI implementation. Implementation highlights below.

Define your interface and class.

public interface ITestService
{
 int GetTest();
}

public class TestService : ITestService
{
 public int GetTest()
 {
 return 111;
 }
}

Update your controller to have dependency injected into constructor.

public partial class HomeController : Controller
 {
 private readonly ITestService _testService;

 public HomeController(ITestService testService)
 {
 _testService = testService;
 }

 public virtual ActionResult Index()
 {
 ViewBag.Test = _testService.GetTest();
 return View();
 }
 }

Add ViewBag.Test output to your view.


_testService.GetTest() output: @ViewBag.Test

Now let’s add Simple Injector nuget package into your web project.

Install-Package SimpleInjector.Integration.Web.Mvc

And following Simple Injector MVC integration documentation, let’s configure our dependencies resolver in Global.asax file.


        protected void Application_Start()
        {
            // default MVC stuff
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            // Simple Injector set up
            var container = new Container();
            container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
            // Register your stuff here  
            container.Register<ITestService, TestService>(Lifestyle.Scoped);
            container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
            container.RegisterMvcIntegratedFilterProvider();
            container.Verify();
            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
        }

And the magic happened. On the home page you can see 111 output of coming from TestService, which was instantiated by Simple Injector.

Source code available on GitHub: https://github.com/ignas-sakalauskas/SimpleInjectorMvc5

Give it a go.