logo

C# How to use dependency injection using Unity resolver

Overview: This code sample demonstration how to use Dependency Injection in Web API with Unity. DI uses interface class as the base class. The concrete class is determined by the unity resolver as it search the container for register interfaces and their associated concrete class. The resolver instantiates the concrete class when an interface variable is assigned. In this case the people controller injects the AddressBookRepository when begin assigned to the IAddressBookRepository variable. This is called constructor injection or setter injection. The IDependencyResolver interface is used for resolving dependencies. The IDependencyResolver interface has two methods: GetService and GetServices.

nuGet

1. nuGet Microsoft.Extensions.DependencyInjection and Unity

WebApiConfig.cs

1. Create the Unity Container
2. Register the custom interface classes and the concrete class with the container
3. Associate the UnityResolver with Unity Container

using Microsoft.Practices.Unity;
using OpenPO.Services;
using OpenPO.Resolver;

   public static void Register(HttpConfiguration config)
        public static void Register(HttpConfiguration config)
        {
       
            var container = new UnityContainer();
            container.RegisterType<IAddressBookRepository, AddressBookRepository>(new HierarchicalLifetimeManager());
            config.DependencyResolver = new UnityResolver(container);
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

Unity resolver

using Microsoft.Practices.Unity;
using System.Web.Http.Dependencies;

namespace OpenPO.Resolver
{
    public class UnityResolver : IDependencyResolver
    {
        protected IUnityContainer container;
        public UnityResolver(IUnityContainer container)
        {
            if (container == null)
            {
                throw new ArgumentException("container");
            }
            this.container = container;
        }
        public object GetService(Type serviceType)
        {
            try
            {
                return container.Resolve(serviceType);
            }
            catch (ResolutionFailedException)
            {
                return null;
            }
        }
        public IEnumerable<object> GetServices(Type serviceType)
        {
            try {
                return container.ResolveAll(serviceType);
            }
            catch (ResolutionFailedException)
            {
                return new List<object>();
            }
        }
        public IDependencyScope BeginScope()
        {
            var child = container.CreateChildContainer();
            return new UnityResolver(child);
        }
        public void Dispose()
        {
            container.Dispose();
        }
    }
}

People Web Api Controller

1. Create the dependency injection by assigning an custom interface in the constructor

 public class PeopleController : ApiController
 {
        private IAddressBookRepository _addressBookRepository;

        
	public PeopleController( IAddressBookRepository addressBookRepository)
      
  	{
                 
 	_addressBookRepository = addressBookRepository;
        
	}
}

Interface and concrete class

 public interface IAddressBookRepository
    {
        void DeleteAddressBook(long paramAddressId);
        void UpdateAddressBook(AddressBook addressBookUpdate);
        AddressBook GetAddressBook(long? paramAddressId);
        List GetPersonList(string keyCode);
        List GetAllAddressBooks(string searchString, string keyCode);
    }
    public class AddressBookRepository:IAddressBookRepository
    {
       ...
     }

Startup.cs

   public void ConfigureServices(IServiceCollection services)
        {
          

            services.AddTransient<IAddressBookRepository, AddressBookRepository>();
            services.AddTransient<IAcctRecRepository, IAcctRecRepository>();
            services.AddTransient<IPOQuoteRepository, POQuoteRepository>();
        }
s