Home » ASP » ASP.MVC » How to use Unity with Web API

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.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

One Response so far.

  1. Kasey says:

    Hey just wanted to give you a quick heads up. The words in your article seem to be
    running off the screen in Ie. I’m not sure if this is a format issue or something to do
    with internet browser compatibility but I thought I’d post to let you know.

    The style and design look great though! Hope you get the problem fixed soon. Kudos

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.