Search code examples
asp.net-mvcdependency-injectionasp.net-web-api2unity-container

What is the common hook up point for a proper Dependency Injection with MVC5 and WebApi2 controllers?


I have both MVC controllers and WebApi controllers in the same project. I would like to inject a service and a logger into controllers through their constructor. Is a DependencyResolver a proper point of extensibility? Can I achieve sharing the same service and logger by both MVC controllers and WebApi controllers? I use Unity as my IoC container.


Solution

  • WebAPI and MVC are completely independent frameworks. Each of them supports DI, and they are designed to work in the same project provided you implement both System.Web.Mvc.IDependencyResolver (or System.Web.Mvc.IControllerFactory) and System.Web.Http.IDependencyResolver in your composition root.

    Generally speaking most major DI containers have NuGet packages that make the integration somewhat easy, but you will have to consult the documentation on the container you use.

    Here is an article which goes over the details of how to integrate Unity. Install the Unity.WebApi and Unity.Mvc5 packages and add your configuration as follows.

    using Microsoft.Practices.Unity;
    using System.Web.Http;
    using System.Web.Mvc;
    
    namespace WebApplication1
    {
        public static class UnityConfig
        {
            public static void RegisterComponents()
            {
                var container = new UnityContainer();
    
                // register all your components with the container here
                // it is NOT necessary to register your controllers
    
                // e.g. container.RegisterType<ITestService, TestService>();
    
                DependencyResolver.SetResolver(new Unity.Mvc5.UnityDependencyResolver(container));
    
                GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
            }
        }
    }