Registering with Microsoft Unity an interface to a concrete class with multiple constructors

If you are using inversion of control, you may come into the scenario that you want to register your interface to a concrete class that has multiple constructors. Registering with Microsoft Unity an interface to a concrete class with multiple constructors is something that require to specify to Unity which of the constructor to use.

container
    .RegisterType<IMainDbContext, MainDbContext>();

The code above can work if MainDbContext has only one constructor. Even if this one require several parameters, it does not matter. Unity will try to solve every parameters. However, in the case that MainDbContext has several constructor, Unity does not know which one to evaluate. Well, that is not totally true. In fact, Microsoft Unity try the one with the most parameters. This can be problematic if you have more than one parameter with the same amount of parameters.

To select which constructors you have to use the InjectionConstructor class. This class allows to specify parameters type. You can use the ResolvedParameter that is generic. You can specify for every parameters the type you want.

container
     .RegisterType<IMainDbContext, MainDbContext>(
        new InjectionConstructor(
            new ResolvedParameter<IRunningContext>()
        )
     );

As you can see, this indicate to Microsoft Unity to resolve the IRunningContext from its container to inject the object into the single parameter constructor of MainDbContext. In that case, we take the single constructor of MainDbContext that has its parameter of IRunningContext.

How to use Unity with Web API

Web Api controller are instantied by Asp.Net MVC framework and by default, the parameter less constructor is called. If you want to instantiate your class with your IoC, like Microsoft Unity, you will have to customize the instantiation of those Web Api Controller. The customized instanciator is called a Dependency Resolver and can be configured in the Global.asax.

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

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

        UnityConfiguration.Initialize();
        MapperConfiguration.Initialize(UnityConfiguration.Container.Resolve<IMapperFactory>());
        UnityConfiguration.Container.Resolve<IDatabaseContext>().InitializeDatabase();
        GlobalConfiguration.Configuration.DependencyResolver = new IoCContainer(UnityConfiguration.Container);
    }
}

The first thing to do is to modify the Application_Start of your WebApi project. You need to execute the configuration of all your interface with Unity. In the example above, this is done by calling UnityConfiguration.Initialize() which Resolve every interface to a concrete class.

The second thing to do is to set to the GlobalConfiguration a DependencyResolver to a IocContainer that we will create to use Unity container.

internal class ScopeContainer : IDependencyScope
{
	protected readonly IUnityContainer _container;

	public ScopeContainer(IUnityContainer container)
	{
		if (container == null)
		{
			throw new ArgumentNullException("container");
		}
		this._container = container;
	}

        public object GetService(Type serviceType)
        {

            if (!_container.IsRegistered(serviceType))
            {
                if (serviceType.IsAbstract || serviceType.IsInterface)
                {
                    return null;
                }
            }
            return _container.Resolve(serviceType);
        }

	public IEnumerable<object> GetServices(Type serviceType)
	{
		return _container.IsRegistered(serviceType) ? _container.ResolveAll(serviceType) : new List<object>();
	}

	public void Dispose()
	{
		_container.Dispose();
	}
}

internal class IoCContainer : ScopeContainer, IDependencyResolver
{
	public IoCContainer(IUnityContainer container):base(container)
	{
	}

	public IDependencyScope BeginScope()
	{
		var child = _container.CreateChildContainer();
		return new ScopeContainer(child);
	}
}

The GetService is made in a way that it doesn’t require you to register every controllers with Unity but only registered type will go through Unity.

From here, every Web Api controllers will be instanced by passing by the ScopeContainer , which will check every parameters’ type and resolve the type with Unity.

The Web Api will create a new instance of Unity and dispose of it at every http request.

Unity Life time management

When you use Unity to get an instance of a class, Unity pass through the life time manager. The life time manager responsibility is indicate to unity how to instance the class into an object. This one may already have an instanced object for the class requested and thus give this one instead of creating a new instance.

TransientLifetimeManager

TransientLifetimeManager is the default life time manager used by Unity if none is specified. This is the simplest form of life time manager. It creates a new instance every time unity need an instance of the class.

var container = new UnityContainer();
container
    .RegisterType(typeof(IMyClass), typeof(MyClass), "namedMyClass")
    .RegisterType(typeof(IMyClass), typeof(MyClass), "named2MyClass", new TransientLifetimeManager());

In the above example, you can see two registrations with unity of IMyClass interface with the concrete implementation of MyClass. Both of them are using the TransientLifetimeManager. The first one is implicit because it use the default life time manager, while the second is explicit by having a third parameters which specify to use TransientLifetimeManager life time manager.

Singleton

The singleton is pattern (or anti-pattern) that specify that only one instance will live in memory. With Unity, the singleton life time manager is called ContainerControlledLifetimeManager. The ContainerControlledLifetimeManager will instance on the first call the class into an object and all subsequent call will simply give a pointer (reference) to the same object.

var container = new UnityContainer();
container
    .RegisterType(typeof(IMyClass), typeof(MyClass), "SingletonMyClass", new ContainerControlledLifetimeManager());

Of course, it’s only possible to use the explicit registration for singleton since the implicit would create a TransientLifetimeManager. A small note before we pass to the next life time manager : if you are using a web application, beware that the object will be shared between all your users.

Others life time manager

Unity does have multiple others life time manager like PerThreadLifetimeManager or PerResolveLifetimeManager. Both of them won’t be discuss there. The first one can be useful with a system where you are using parallel operations and the last one in some custom case where the life time manager need to be re-created every time.

In a web application, the default life time, TransientLifetimeManager, is the one to use. It will create an instance per web request. Of course, ContainerControlledLifetimeManager is also used in the case of instancing the data access layer, the caching system, the logging system, etc. Those are used across the system without containing “user” objects.

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

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.