Chitika

April 6, 2012

Dependency Injection in ASP.NET MVC 4 and WebAPI using Unity

In this post, I will demonstrate how to use Dependency Injection in ASP.NET MVC 4 application and WebAPI using Unity. The new ASP.NET MVC 4 is a great framework for building web applications and WebAPI is a great for building HTTP services. I will use Unity IoC container to provide the integration with ASP.NET MVC 4 and WebAPI for applying dependency injection.

Using Unity in ASP.NET MVC 4


The following command in the Package Manager console will install Unity.Mvc3 package into your ASP.NET MVC 4 WebAPI application.

PM > Install-Package Unity.Mvc3

Unity.Mvc3 is a package that allows simple Integration of Microsoft's Unity IoC container with ASP.NET MVC 3. It also works great for ASP.NET MVC 4.

After installation of the package you will find the Bootstrapper.cs file in the root of your ASP.NET MVC 4 WebAPI project. The course code of that file is:

    public static class Bootstrapper
    {
        public static void Initialise()
        {
            var container = BuildUnityContainer();

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }

        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();

            // register all your components with the container here
            // e.g. container.RegisterType<itestservice, testservice="">();            

            return container;
        }
    }

We will return to this class a little bit later.

To get started, we should add a call to Bootstrapper.Initialize() in the end of the Application_Start method of Global.asax.cs and the MVC framework will then use the Unity.Mvc3 DependencyResolver to resolve your components.

        protected void Application_Start()
        {
            // Default code of the method
            // . . .

            // Initialization of our Unity container
            Bootstrapper.Initialise();
        }


Using Unity in ASP.NET MVC 4 WebAPI


Unfortunately Unity.Mvc3 doesn't change the DependencyResolver for WebAPI. I hope it will be implemented in Unity.Mvc4.
However, there is the nuget package that has already implemented needed functionality - Unity.WebAPI.

The following command in the Package Manager console will install Unity.WebAPI package into your ASP.NET MVC 4 WebAPI application.

PM > Install-Package Unity.WebAPI

Unity.WebAPI is a library that allows simple Integration of Microsoft's Unity IoC container with ASP.NET's WebAPI. This project 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.

After installation of the package you just have to add one line of code to your Bootstrapper class into the Initialise method:

        public static void Initialise()
        {
            var container = BuildUnityContainer();

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));

            // register dependency resolver for WebAPI RC
            GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
            // if you still use the beta version - change above line to:
            //GlobalConfiguration.Configuration.ServiceResolver.SetResolver(new Unity.WebApi.UnityDependencyResolver(container));
        }

After that you are ready to create your business logic.

Create service


Let's start with the service class that we want to use in our containers.

First, we will create the interface:

    public interface IValuesService
    {
        int Create(string value);
        string Update(int id, string value);
        void Delete(int id);

        IDictionary<int, string> GetAll();
        string Get(int id);
    }

And the service class which contains realization of this interface:

    public class ValuesService : IValuesService
    {
        private Dictionary<int, string> _values;

        public ValuesService()
        {
            _values = new Dictionary<int, string>
                          {
                              {1, "Value 1"},
                              {2, "Value 2"},
                              {3, "Value 3"},
                              {4, "Value 4"},
                              {5, "Value 5"},
                          };
        }

        private int GetNextId()
        {
            return _values.Keys.Max() + 1;
        }

        public int Create(string value)
        {
            var id = GetNextId();
            _values.Add(id, value);
            return id;
        }

        public string Update(int id, string value)
        {
            _values[id] = value;
            return Get(id);
        }

        public void Delete(int id)
        {
            _values.Remove(id);
        }

        public IDictionary<int, string> GetAll()
        {
            return _values;
        }

        public string Get(int id)
        {
            return _values[id];
        }
    }


This is the really simple service with some predefined values in the constructor (just for this simple example). Of course in the real life your services will be much more complex.

Register service


The next step is register our service and interface in Unity container. This is very simple, you just have to add one line of code to the Bootstrapper class into the BuildUnityContainer method:

        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();

            // register values service
            container.RegisterType<IValuesService, ValuesService>();

            return container;
        }

As you can see it is really simple.
Also, if you read this method carefully you should see that Unity.Mvc3 registered all of our controllers by default in the Unity container. This is the line where it's happened:

            container.RegisterControllers();


Inject service to Controller


So, let's get our service in the home controller:

    public class HomeController : Controller
    {
        private readonly IValuesService _valuesService;

        public HomeController(IValuesService valuesService)
        {
            _valuesService = valuesService;
        }

        public ActionResult Values()
        {
            var viewModel = _valuesService.GetAll();

            return View(viewModel);
        }


        // old code
        public ActionResult Index()
        {
            return View();
        }
    }

I've just added the constructor which receive IValuesService as a parameters. And Unity will do all the "magic" of resolving out service interface for us.
Then. to test it, let's create a simple view named as the same as the action - Values.cshtml (tip: you can create a view just clicking the right mouse button on the action name, and selecting 'Add View...' in the context menu):

@model Dictionary<int,string>

@{
    ViewBag.Title = "Values";
}

<h2>Values</h2>

<ul>
    @foreach(var item in Model)
    {
        <li>ID: @item.Key, Value: @item.Value</li>
    }
</ul>

Then, compile our solution and run it.
Then, navigate to http://localhost:<your port number>/Home/Values. You should see the list of the five values with ID.
If you see it then injection for our Controllers works properly.

Inject service to ApiController


Next, let's inject our service to ApiControllers:

    public class ValuesController : ApiController
    {
        private readonly IValuesService _valuesService;
        
        public ValuesController(IValuesService valuesService)
        {
            _valuesService = valuesService;
        }

        // GET /api/values
        public IEnumerable<KeyValuePair<int, string>> Get()
        {
            return _valuesService.GetAll();
        }

        // GET /api/values/5
        public string Get(int id)
        {
            return _valuesService.Get(id);
        }

        // POST /api/values
        public void Post(string value)
        {
            _valuesService.Create(value);
        }

        // PUT /api/values/5
        public void Put(int id, string value)
        {
            _valuesService.Update(id, value);
        }

        // DELETE /api/values/5
        public void Delete(int id)
        {
            _valuesService.Delete(id);
        }
    }

To test is everything fine with the ApiController, just compile the solution and run it.
After that, open the IE developers tools and click the 'Start capturing' button in the Network tab.
Then, navigate to http://localhost:<your port number>/api/values.
You should see something like this in the Response body tab:

[{"key":1,"value":"Value 1"},{"key":2,"value":"Value 2"},{"key":3,"value":"Value 3"},{"key":4,"value":"Value 4"},{"key":5,"value":"Value 5"}]

So, for now all of your Controllers and ApiControllers can use your services.

That's all.

UPDATED:
You can download sources at: UnityApplication14.zip

84 comments:

  1. I'm so happy that I've found this blog!

    ReplyDelete
  2. I'll have to second that. This post saved me from having to figure this out and spending some time on it. going to use that time to check out the other posts

    ReplyDelete
    Replies
    1. I'm happy about that. There are not many posts yet, but i'm working on it.

      Delete
  3. Andrew: When I get to the line that says to add this to the bootstrapper "GlobalConfiguration.Configuration.ServiceResolver.SetResolver(new Unity.WebApi.UnityDependencyResolver(container));", there is no ServiceResolver property available on Configuration. Is there something I'm missing?
    thanks,
    Colin

    ReplyDelete
    Replies
    1. Hello Colin, that because I wrote this article for ASP.NET MVC 4 Beta, but you use ASP.NET MVC 4 RC. In that case you have to change this line to:
      GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);

      Delete
    2. I've changed the code in the article

      Delete
  4. This is nice and informative post, Thanks to post.

    Asp.net Development

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. why is the service IValueService injected into constructor of controller? Why not just access a ServiceLocator from the controller methods?

    public IEnumerable> Get()
    {
    return ServiceLocatorOfSomeKind().GetAll();
    }

    ReplyDelete
    Replies
    1. Well, it depends. I use the rule: If the class cannot do its job w/o the dependency, then add it to the constructor. But if the class can work w/o the dependency, a setter is fine.

      Also good overview about injection made by Martin Fowler:
      http://martinfowler.com/articles/injection.html#ConstructorVersusSetterInjection

      Delete
  7. On debug i get the following exception:
    {"The type Unity.WebApi.UnityDependencyResolver does not appear to implement Microsoft.Practices.ServiceLocation.IServiceLocator.\r\nParameter name: commonServiceLocator"}

    Also : Microsoft.Practices.Unity.UnityContainer' does not contain a definition for 'RegisterControllers' and no extension method 'RegisterControllers' accepting a first argument of type 'Microsoft.Practices.Unity.UnityContainer' could be found (are you missing a using directive or an assembly reference?)

    It would be very helpful if you publish a working project for downloading and studying.

    ReplyDelete
    Replies
    1. I think you have to reinstall the Unity.WebAPI nuget package. And be sure that you use ASP.NET MVC 4.0 RC, if you still use the beta version I suggest to move to RC ASAP.

      Delete
    2. For now you should use: Unity v2.1.505.2, Unity.WebAPI v0.10, Unity.Mvc3 v1.2, ASP.NET MVC 4 (RC) v4.0.20505.0, ASP.NET Web API (RC) v4.0.20505.0

      Delete
    3. Also, RegisterControllers() method doesn't needed anymore. I've updated the post. Thanks.

      Delete
    4. I'm working with the version of MVC4 that is installed with VS2012 RTW. Just a plain old mvc4 site, no webapi stuff yet. Anyway, I'm getting the message that "The type Unity.Mvc3.UnityDependencyResolver does not appear to implement Microsoft.Practices.ServiceLocation.IServiceLocator." when I call "DependencyResolver.SetResolver(New UnityDependencyResolver(container))". I've tried uninstalling and reinstalling Unity.MVC3. Didn't help. Any ideas?

      Delete
    5. I think you have to update your MVC libraries. The latest version is 4.0.20710.0. You can do it easily by RMB click on 'References' of your project and then click 'Manage NuGet Packages...'. Then select 'Updates' on the left panel and update ASP.NET MVC 4 to the latest version. Do it the same for ASP.NET Web API.

      Delete
    6. I've updated all my libraries as mentioned and i'm still getting the missing IserviceLocator implementation exception while running this line :

      DependencyResolver.SetResolver(new UnityDependencyResolver(container));

      any ideas?

      Delete
    7. I've included the sources to this topic. Enjoy.

      Delete
    8. The UnityDependencyResolver included in Unity.WebApi does not appear to inherit from IServiceLocator (hence the rather annoying explosion). All you need to do is to wrap this class with the interface. I found that this works a treat:

      public class CustomUnityDependencyResolver : UnityDependencyResolver, IServiceLocator
      {
      public CustomUnityDependencyResolver(IUnityContainer container) : base(container) {}

      public object GetInstance(Type serviceType)
      {
      return Container.Resolve(serviceType);
      }

      public object GetInstance(Type serviceType, string key)
      {
      return Container.Resolve(serviceType, key);
      }

      public IEnumerable<object> GetAllInstances(Type serviceType)
      {
      return Container.ResolveAll(serviceType);
      }

      public TService GetInstance()
      {
      return Container.Resolve();
      }

      public TService GetInstance(string key)
      {
      return Container.Resolve(key);
      }

      public IEnumerable GetAllInstances()
      {
      return Container.ResolveAll();
      }
      }



      Delete
    9. Make sure you run "Install-Package Unity.Mvc3" on NuGet's PM Console. The author listed it as the first instruction in this article.

      This line of code will need it:
      DependencyResolver.SetResolver(new UnityDependencyResolver(container));

      Delete
  8. Well done - stuck to basics for those of us who are not yet Web API geniuses!

    ReplyDelete
  9. Hi, Andrew! I've a problem with GlobalConfiguration which is highlighted in red.

    GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);

    Any idea?

    Thx

    ReplyDelete
  10. Hi Andrew, Great post!
    I've got couple of questions :

    1. Can i inject the API controllers instead of the services by registering them?
    2. Can i register the services via the web.config in the unity configuration sections?

    thx,
    Gadi.

    ReplyDelete
    Replies
    1. Hello Gadi,
      > 1. Can i inject the API controllers instead of the services by registering them?
      Why do you need it?

      >2. Can i register the services via the web.config in the unity configuration sections?
      Yes, you can. See: http://blogs.msdn.com/b/benoitsarie/archive/2010/09/18/unity-2-configuration-file-and-unity-part-2.aspx

      Delete
  11. I'm getting an error regarding missing default constructor for the values api controller.
    how does the valuesServices is resolved?
    meaning how is it transfered to this controller?

    ReplyDelete
  12. Saved my time. Appreciate explaining the WebAPI part to us DI numbskulls. :-)

    ReplyDelete
  13. Hi Andrew,

    Can I use this for MVC3? Should I make any changes?
    Thanks.

    ReplyDelete
  14. This comment has been removed by the author.

    ReplyDelete
  15. Instead of

    private readonly Dictionary _values;

    public ValuesService()
    {
    _values = new Dictionary
    {
    {1, "Value 1"},
    {2, "Value 2"},
    {3, "Value 3"},
    {4, "Value 4"},
    {5, "Value 5"},
    };
    }

    I would like to do something like this (sending dbcontext as parameter to the constructor):

    private readonly IEfContext _context;

    public ValuesService(IEfContext _context)
    {
    _context = context;
    }

    how should i modifi the following line:

    container.RegisterType();

    in the Bootstrapper class?

    Thanks.

    ReplyDelete
  16. Really good thanks, simplifies what some seems to make sound over complicated. Cheers

    ReplyDelete
  17. Thank you Sir. That helped me out a bunch.

    ReplyDelete
  18. Any hints on how to use that with VS2013, MVC5 and WebAPI 5 ?

    ReplyDelete
    Replies
    1. I am stuck there too. Any help on using Unity container on MVC5 WebAPI please? I was using NInject and it is broken when i migrate to VS 2013. Then i decided to switch to Unity thinking everything will go smooth but here i am stuck. Any help will be appreciated.

      Delete
  19. Really appreciate it. Couldn't find anything simple like this taking about DI implementation.

    ReplyDelete
  20. Be careful with UnityDependencyResolver!!!

    We have had huge issues using it with Entity Framework DbContexts. It boils down to scope and how unity wasn't creating new DbContexts for each web request. You need a new DbContext for each request else you will start getting tough Entity Framework issues due to the reuse of DbContext over mulitple requests.

    If you use unity to inject DbContext to your controllers, see this post and implement UnityResolver : IDependencyResolver from the post:

    http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver

    Steve

    ReplyDelete
  21. Gaining Python certifications will validate your skills and advance your career.
    python certification

    ReplyDelete
  22. Thanks for sharing,excellent information.It is very useful for me to learn and understand easily.Tableau is a powerful and fastest growing data visualization tool used in the Business Intelligence Industry. Business Intelligence Industry suggest to take tableau course to enhance their skills
    tableau training institute in bangalore

    ReplyDelete

  23. Thanks for sharing such a great information.It is really one of the finest article and more informative too. I want to share some informative data about c# training and c# training videos . Expecting more articles from you.

    ReplyDelete
  24. That is nice article from you, this is informative stuff. Hope more articles from you . I also want to share some information about bw Training

    ReplyDelete
  25. Compre documentos en línea, documentos originales y registrados.
    Acerca de Permisodeespana, algunos dicen que somos los solucionadores de problemas, mientras que otros se refieren a nosotros como vendedores de soluciones. Contamos con cientos de clientes satisfechos a nivel mundial. Hacemos documentos falsos autorizados y aprobados como Permiso de Residencia Español, DNI, Pasaporte Español y Licencia de Conducir Española. Somos los fabricantes y proveedores de primer nivel de estos documentos, reconocidos a nivel mundial.

    Comprar permiso de residencia,
    permiso de residenciareal y falso en línea,
    Compre licencia de conducir en línea,
    Compre una licencia de conducir española falsa en línea,
    Comprar tarjeta de identificación,
    Licencia de conducir real y falsa,
    Compre pasaporte real en línea,

    Visit Here fpr more information. :- https://permisodeespana.com/licencia-de-conducir-espanola/
    Address: 56 Guild Street, London, EC4A 3WU (UK)
    Email: contact@permisodeespana.com
    WhatsApp: +443455280186

    ReplyDelete
  26. IGRS Telangana portal is the all type services provide in telangana state

    ReplyDelete
  27. KGF 2 Release Date : Directed by Prashanth Neel. With Yash, Sanjay Dutt, Raveena Tandon, Prakash Raj. The blood-soaked land of Kolar Gold Fields

    ReplyDelete
  28. Great post informative content.
    https://whatsappdelta.com/

    ReplyDelete
  29. https://zippyshare.com/sites/priv/accountSettings.jsp

    ReplyDelete
  30. https://mydrivers.online/software/intel-wifi-6-ax201-driver-for-windows/

    ReplyDelete
  31. One of the best articles is this. I am looking for this article for a long time. At last, I found this on your website. Many many thanks for sharing your content.
    Bangla Calendar 2022
    Cool and beautiful stylish name

    ReplyDelete
  32. Oppo launch First foldable smartphone .Oppo has teased the company’s first foldable phone.The image of the device is only shown from the spine side and we get a glimpse of the phone’s profile, revealing what appears to be a triple camera setup Article
    Click Here For website

    ReplyDelete
  33. i like your post and all your headings are good....hindi skill

    ReplyDelete
  34. I needed to gratitude for this prominent appropriate to apply!! I truly adored all minuscule piece of it. I have you bookmarked your site to try out the presented assets you articulate. Sony Vegas Pre Cracked

    ReplyDelete
  35. Goodness! Such an awesome and helpful call that is. I basically in all actuality praise it. it's for that excuse attractive and as an end result impressive. I'm recently stunned. I dream that you keep up with to make a get adhering to of your seriously be sick bearing in considerations this in the with moreover!thanks Microsoft Office 2010 Cracker

    ReplyDelete
  36. Thank you sir, I like your thoughts and your ideas this article, and your creativity logic, This is a wonderful article.I will helpful this article. by the way we have one of the best hard disk cleaner called WinDirStat which will clean your all un needed filed from your PC

    ReplyDelete
  37. Thanks for the great content,I will also share it with my friends & once again Thanks a Lot.OnlyFansYT

    ReplyDelete
  38. It’s clearly an exceptional and very useful fact. Thanks for sharing this helpful data with us. CEA Aviation is one of the DGCA Ground Classes in delhi . It gives admission to all of the aspirants seeking to start with Ground classes. You can enrol for Best Ground training for DGCA checks with us. Once you're clear with DGCA exam Counsellor Desk will assist you in choosing the best flight academy overseas.

    ReplyDelete
  39. Step-by-Step Hacking Tutorials about WiFi hacking,
    Kali Linux, Metasploit, exploits, ethical hacking, information security, malware analysis and scanning
    hacking Tutorial

    ReplyDelete
  40. FappTime.com is the ultimate destination for free Onlyfans leaks. As a new website, we keep our users updated with daily videos of creators from Onlyfans, Fansly, Patreon, and other popular websites. The website is designed to be mobile-friendly, ensuring a seamless browsing experience on all devices. Our website also provides the option of downloading videos, allowing users to watch their favorite content anytime, anywhere. Whether you're a fan of Onlyfans or simply looking for a new source of free content, FappTime.com is your go-to website.

    ReplyDelete
  41. The provided code snippet demonstrates how to use Unity IoC container for implementing Dependency Injection in an ASP.NET MVC 4 and WebAPI application. Here's a breakdown of the code:

    To start using Unity in ASP.NET MVC 4, you need to install the Unity.Mvc3 package. You can do this by running the following command in the Package Manager Console:

    PM > Install-Package Unity.Mvc3
    ```

    After installing the package, you will find the Bootstrapper.cs file in the root of your ASP.NET MVC 4 WebAPI project. This file contains a static class named Bootstrapper.

    The Bootstrapper class has a static method called Initialise(), which is responsible for initializing the Unity container and configuring the Dependency Resolver.

    The BuildUnityContainer() method creates a new instance of the Unity container and returns it. You can register your components with the container inside this method.

    To register your components, you can use the RegisterType() method of the Unity container. For example:
    csharp

    container.RegisterType();
    ```

    This code registers `ITestService` interface with the `TestService` class as the implementation.

    Finally, the DependencyResolver.SetResolver() method is used to set the UnityDependencyResolver as the Dependency Resolver for the application. This will enable ASP.NET MVC 4 to resolve dependencies using Unity.
    Jobs Listings
    Visit Serafelagi.com!
    By following these steps and registering your components with the Unity container, you can leverage the power of Dependency Injection in your ASP.NET MVC 4 and WebAPI application.

    ReplyDelete