Search Sreeni's Insights

Filter by content type
crafting February 17, 2015 7 min read

How to use Dependency Injection with an IoC container in ASP.NET MVC?

Dependency Injection and IoC containers explained through Unity and Autofac setup in ASP.NET MVC 5, including object lifetimes and practical container wiring.

Share:

How to use Dependency Injection with an IoC container in ASP.NET MVC?

In the previous article, we discussed the Dependency Inversion Principle, where the business classes should depend on abstractions and not on concrete classes. But someone has to create the concrete classes and pass them in. If we do it manually in every controller, the code is becoming messy very quickly. This is where Dependency Injection (DI) and an Inversion of Control (IoC) container comes for the rescue. In this article, we are going to see what is DI, why we need an IoC container and how to set it up in ASP.NET MVC 5 with two popular containers, Unity and Autofac.

TL;DR Summary

  • Dependency Injection (DI) is a technique where a class receives its dependencies from outside instead of creating them.
  • Inversion of Control (IoC) container is a library which creates the objects and injects the dependencies automatically.
  • Prefer constructor injection, it makes the dependencies visible and mandatory.
  • ASP.NET MVC 5 supports DI through IDependencyResolver.
  • Unity and Autofac both work well with MVC 5, choose based on your team’s familiarity.
  • Choose the right lifetime (transient, per request, singleton), otherwise you will get memory leaks or shared state bugs.
  • Register everything at one place, i.e. the composition root.

Challenges

new everywhere

Without DI, the controller creates the service, the service creates the repository and the repository creates the DbContext. The controller is tightly coupled with the full chain. It is not possible to write a unit test for the controller without hitting the database.

Poor man’s DI is not scaling

Some teams start with “poor man’s DI”, a default constructor which calls the other constructor with concrete classes. It works for few controllers, but when the application has 50 controllers and each service has 3-4 dependencies, maintaining these constructors is a pain, and changing one dependency means touching many files.

Lifetime bugs

When the same DbContext instance is shared across requests by mistake, we get strange errors and stale data. When a new instance is created for every small call, we lose the unit of work. Managing the lifetime manually is error-prone.

What is Dependency Injection?

Dependency Injection is a design pattern in which an object receives the other objects that it depends on, instead of creating them itself.

In simple terms, the class says “I need an IFundRepository” in its constructor and somebody else gives it. The class doesn’t care which implementation it is.

Think about a restaurant again. The chef doesn’t go to the market to buy vegetables every time he cooks. Supplier delivers them to the kitchen. The chef only says what he needs. Tomorrow if we change the supplier, the chef keeps cooking the same way.

There are three common ways to inject,

  • Constructor injection - dependencies are passed via constructor. It is the recommended approach.
  • Property injection - dependencies are set via public properties. Use only for optional dependencies.
  • Method injection - dependency is passed to the method which needs it.

What is an IoC Container?

An IoC container is a framework which knows how to create objects and their dependencies, based on the registrations we give.

Simply put, we tell the container “when someone asks for IFundRepository, give SqlFundRepository”, and the container builds the full object graph for us, including the dependencies of dependencies.

Why IoC container is important?

In order to remove the tight coupling, to make the controllers and services testable and to manage the object lifetime at one place, we should use an IoC container from the beginning of the project. It also keeps the composition logic in one place, called as Composition Root, so when a dependency is changed, we change only one line.

Unity vs Autofac

We can set up DI in ASP.NET MVC 5 with many containers (Ninject, StructureMap, Simple Injector, Castle Windsor, etc.). In this article, we will see the two which we used most,

UnityAutofac
ApproachMicrosoft patterns & practices containerOpen source container from the community
Pros+ Familiar for teams using Microsoft stack<br>+ NuGet package creates the bootstrap code for you<br>+ Good documentation from p&p+ Rich features (modules, assembly scanning, decorators)<br>+ Very good MVC and Web API integration<br>+ Clear lifetime scopes
Cons− Fewer advanced features<br>− Assembly scanning needs extra code− Slightly steeper learning curve<br>− More concepts (scopes, modules) to understand

Both are good choices, it depends on your team’s familiarity and the features you need.

Option1: Using Unity

Steps to Implement:

Follow the following instructions to set up Unity in an ASP.NET MVC 5 application.

  • Open the ASP.NET MVC 5 project in Visual Studio 2013.

  • Install the Unity bootstrapper for ASP.NET MVC from the Package Manager Console.

    Install-Package Unity.Mvc
  • The package adds two files under App_Start folder, UnityConfig.cs and UnityMvcActivator.cs. The activator hooks Unity into MVC’s DependencyResolver automatically when the application starts.

  • Open UnityConfig.cs and register your types in the RegisterTypes method.

    public static void RegisterTypes(IUnityContainer container)
    {
        container.RegisterType<FundsDbContext>(new PerRequestLifetimeManager());
        container.RegisterType<IFundRepository, SqlFundRepository>();
        container.RegisterType<IFundService, FundService>();
    }
  • Add the dependency in the controller constructor.

    public class FundsController : Controller
    {
        private readonly IFundService _fundService;
    
        public FundsController(IFundService fundService)
        {
            _fundService = fundService;
        }
    
        public ActionResult Index()
        {
            return View(_fundService.GetActiveFunds());
        }
    }
  • Just to pulse check, run the application and browse /Funds. If the page is loading, Unity is resolving the controller with its dependencies. If you see “No parameterless constructor defined for this object”, then the activator is not wired, check the WebActivatorEx attributes in UnityMvcActivator.cs.

Option2: Using Autofac

Steps to Implement:

Follow the following instructions to set up Autofac in an ASP.NET MVC 5 application.

  • Install the Autofac MVC 5 integration package.

    Install-Package Autofac.Mvc5
  • Create a new class AutofacConfig.cs under App_Start folder.

    public static class AutofacConfig
    {
        public static void Register()
        {
            var builder = new ContainerBuilder();
    
            builder.RegisterControllers(typeof(MvcApplication).Assembly);
    
            builder.RegisterType<FundsDbContext>().AsSelf().InstancePerRequest();
            builder.RegisterType<SqlFundRepository>().As<IFundRepository>().InstancePerRequest();
            builder.RegisterType<FundService>().As<IFundService>().InstancePerRequest();
    
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }
  • Call it from Application_Start in Global.asax.cs.

    protected void Application_Start()
    {
        AutofacConfig.Register();
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
  • Use the same constructor injection in the controller as shown in Option1. Controller code doesn’t change, that is the beauty of DI.

  • Just to pulse check, run the application and browse /Funds.

Info: If you have many services, use assembly scanning in Autofac instead of registering one by one: builder.RegisterAssemblyTypes(typeof(FundService).Assembly).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces().InstancePerRequest();

Choosing the right lifetime

It is important to choose the right lifetime for each registration, otherwise you will get bugs which are very hard to reproduce. Find below the common lifetimes,

  • Transient - new instance every time it is requested. Use for lightweight, stateless services.
  • Per request - one instance per HTTP request. Use for DbContext and unit of work, so that all repositories in one request share the same context.
  • Singleton - one instance for the whole application. Use only for thread-safe, stateless objects like configuration readers or caches.

Note: Never register DbContext as singleton. DbContext is not thread-safe and it keeps tracking entities, it will grow in memory and multiple requests will step on each other.

Be mindful of “captive dependency”, i.e. a singleton which depends on a per request object. The per request object is captured forever inside the singleton and lives longer than expected.

Best Practices

  • Use constructor injection by default.
  • Keep all registrations in one place (Composition Root), don’t call the container from business classes.
  • Don’t use the container as a Service Locator (DependencyResolver.Current.GetService<T>() inside classes), it hides the dependencies.
  • If a constructor needs more than 4-5 dependencies, it is a sign the class is doing too much (SRP violation).
  • Register against interfaces, not concrete classes, so you can replace them in tests.

Wrap up

In this article, we have looked at what is Dependency Injection, why we need an IoC container, how to set up Unity and Autofac in ASP.NET MVC 5 and how to choose the right lifetime. I hope this article provided you some insights into DI and IoC containers. In the next article, I will walk you through why we must not use magic numbers and hard-coding.

Related Posts