Using Unity with ASP.NET WEB API Controller

Support for Ioc containers is backed into ASP.NET WEB API and uses the service locator pattern dependency resolver by default.

the default service locator implements the IDependencyResolver interface. This interface has two methods.

  • GetService: Creates one instance of a specified type.
  • GetServices: Create a collection of objects of a specified type.

in order to use Microsoft Unity framework with ASP.NET WEB API we need to map these to methods to Resolve and ResolveAll methods of Utity. to do so first add the following method to your global.asax.cs or your bootstrapper class

        Public static void RegisterDependencies(IUnityContainer container)
        {
 
            GlobalConfiguration.Configuration.ServiceResolver.SetResolver(
                t =>
                {
                    try
                    {
                        return container.Resolve(t);
                    }
                    catch (ResolutionFailedException)
                    {
                        return null;
                    }
                },
                t =>
                {
                    try
                    {
                        return container.ResolveAll(t);
                    }
                    catch (ResolutionFailedException)
                    {
                        return new List<object>();
                    }
                });
        }

this is the method which maps the GetService and GetServices methods to Resolve and ResolveAll methods.

the next and final step is to plug in this method to the framework. to do so you just need to call this method from the method in which you construct your unity container. in my case I create a separate method to take care of this:

        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();
            RegisterMappers(container);
            RegisterDependencies(container);
            container.RegisterControllers();
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
            return container;
        }

and you are done. you should be able to use your Ioc container with ASP.NET WEB API now.

Written by vahid

Saturday, April 14, 2012 at 5:40 PM

Tagged with , ,

Leave a Reply