Patrick Desjardins Blog
Patrick Desjardins picture from a conference

How to register a class that need a connection string with Unity and Asp.Net MVC

Posted on: 2012-10-05

Microsoft Unity is an the inside Microsoft patterns and practices library (since 2009) as a dependency injection container. It can be used with configuration file or with a fluent API directly inside your .Net project. It supports constructor injection, property injection and also method injection.

With the help of UnityMVC3 library, it can be really easy to setup your dependency injection container to be unique for each http request and to automate the injection of all your controllers automatically without having to map every controller interface to your concrete implementation.

Unity Mvc 3 includes a bespoke DependencyResolver that creates a child container per HTTP request and disposes of all registered IDisposable instances at the end of the request.

First of all, you need to get both library, the Unity and Unity MVC3 (which work perfectly with MVC4).

Then, you need to configure the dependency to your container. This need to be done in the application start of the application which is inside Global.ascx.cs.

protected void Application_Start() { 
  AreaRegistration.RegisterAllAreas();

  WebApiConfig.Register(GlobalConfiguration.Configuration); 
  FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
  RouteConfig.RegisterRoutes(RouteTable.Routes); 
  BundleConfig.RegisterBundles(BundleTable.Bundles); 
  AuthConfig.RegisterAuth();

  var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; 
  UnityConfiguration.Initialize(connectionString); 
} 

The line 13 initialize Unity. This class is a custom one that take the connection string that will be injected for the database. If we go inside the UnityConfiguration class we will see that all my interface are mapped to concrete type.

public static class UnityConfiguration { 
  public static void Initialize(string connectionString) { 
    IUnityContainer container = new UnityContainer() 
    .RegisterType<IDatabaseContext, DatabaseContext>(new InjectionConstructor(connectionString)) 
    .RegisterType<IRepositoryFactory, RepositoryFactory>() 
    .RegisterType<IWorkoutService, WorkoutService>() 
    .RegisterType<IWorkoutRepository, WorkoutRepository>();

    DependencyResolver.SetResolver(new UnityDependencyResolver(container)); 
  } 
} 

You can notice that the DatabaseContext has a parameter. To pass the connection string to my DatabaseContext I used the InjectionConstructor object and pass the connection string. The latest version stable version of Unity, version 2.1, doesn't require you to write anything more to have all you controller injected. In fact, I have a IWorkoutController and you do not see it inside this configuration.

The last step is to register the resolver to be used for the http request of each user. This is done by using the DependencyResolver.SetResolver method.