How to register a class that need a connection string with Unity and Asp.Net MVC<!-- --> | <!-- -->Patrick Desjardins Blog
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: October 5, 2012

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.

pnp logo

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.

1protected void Application_Start() {
2 AreaRegistration.RegisterAllAreas();
4 WebApiConfig.Register(GlobalConfiguration.Configuration);
5 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
6 RouteConfig.RegisterRoutes(RouteTable.Routes);
7 BundleConfig.RegisterBundles(BundleTable.Bundles);
8 AuthConfig.RegisterAuth();
10 var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
11 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.

1public static class UnityConfiguration {
2 public static void Initialize(string connectionString) {
3 IUnityContainer container = new UnityContainer()
4 .RegisterType<IDatabaseContext, DatabaseContext>(new InjectionConstructor(connectionString))
5 .RegisterType<IRepositoryFactory, RepositoryFactory>()
6 .RegisterType<IWorkoutService, WorkoutService>()
7 .RegisterType<IWorkoutRepository, WorkoutRepository>();
9 DependencyResolver.SetResolver(new UnityDependencyResolver(container));
10 }

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.