My Adventures in Coding

March 27, 2013

C# – Using Unity for Dependency Injection in an ASP.NET MVC 4 Web API

Filed under: .NET,c#,MVC,REST — Brian @ 11:27 pm
Tags: , , ,

When I created my first REST API since I started working with MVC 4 Web API, immediately I wanted to figure out how to handle dependency injection. When I had previously worked in Java I used Spring, in Scala I used Google Guice, and so now I was on the hunt for another dependency injection tool. There are several options out there, such as Spring .NET and also Ninject, however for now we decided to go with Unity because of it’s simple setup and maturity.

With MVC 4 Web API the application creates an instance of the controller class whenever a REST call is made. So for example if you have the REST endpoint /cars it will create an instance of the controller CarsController to service the request. Now, this all works fine until you change the constructor on CarsController to take a parameter. Once you do this, you will need a dependency injection framework to handle knowing how to resolve the dependencies for CarsController when one is being created. So let’s use this as our example.

Note: For this example I am using:
Visual Studio 2012 Express Web and version 2.1.505.2 of the Unity NuGet package.

Now, in Visual Studio 2012 NuGet is built right in, so no need to install the NuGet Plugin anymore (Woohoo!)

Step 1 – Create a new Web API Project

Create a new Web API project in Visual Studio:

  • File -> New Project
  • Installed -> Templates -> Visual C# -> Web
  • Give the project the name: UnityExample
  • Click “OK”
  • Select Project Template -> Web API
  • Click “OK”

That’s all! Now you have a new Web API project called UnityExample.

Step 2 – Install Unity NuGet Package

For installing NuGet packages you can use either the GUI tool or the console.

To use the Package Manager Console tool:

  • To open the console: Tools -> Library Package Manager -> Package Manager Console
  • Now at the console prompt enter the command: Install-Package Unity

Now, if you prefer to use the GUI tool:

  • In Solution Explorer, right click on the solution and select Manage NuGet Packages for Solution
  • Ensure Online is selected, then in the search box type Unity
  • The Unity package will be displayed at the top of the list then click Install

Step 3 – Create an IOC (Inversion of Control) Container

You will need to create an IOC container that impelements IDependencyResolver. I did not write my own, I got this code from here.

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

namespace UnityExample
{
    // This code is from:
    // http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver
    // The website also has a detailed explanation of how to setup dependency injection

    public class ScopeContainer : IDependencyScope
    {
        protected 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))
            {
                return container.Resolve(serviceType);
            }
            else
            {
                return null;
            }
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            if (container.IsRegistered(serviceType))
            {
                return container.ResolveAll(serviceType);
            }
            else
            {
                return new List<object>();
            }
        }

        public void Dispose()
        {
            container.Dispose();
        }
    }

    class IoCContainer : ScopeContainer, IDependencyResolver
    {
        public IoCContainer(IUnityContainer container)
            : base(container)
        {
        }

        public IDependencyScope BeginScope()
        {
            var child = container.CreateChildContainer();
            return new ScopeContainer(child);
        }
    }
}

Step 4 – Create a new class called NameService.cs

The following class with be the dependency that we will inject into our new controller.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace UnityExample
{
    public class NameService
    {
        private string _myName;

        public NameService(string myName)
        {
            _myName = myName;
        }

        public string GetMyName()
        {
            return string.Format("My name is: {0}", _myName);
        }
    }
}

Step 5 – Create a new Controller called NameController which requires NameService as a constructor parameter

To create the new controller NameController:

  • Right click on the Controllers folder and select Add -> Controller
  • Enter Controller name: NameController
  • From the Template drop-down select Empty API controller

Now enter the following code in your new NameController class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace UnityExample.Controllers
{
    public class NameController : ApiController
    {
        private NameService _nameService;

        public NameController(NameService nameService)
        {
            _nameService = nameService;
        }

        public string Get()
        {
            return _nameService.GetMyName();
        }
    }
}

Step 6 – Setup Dependency Injection with Unity in Global.asax.cs

Now the final step is to create an instance of NameService and tell Unity to use that instance anytime an instance of NameController is created.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

// Add usings for Unity and Controllers
using Microsoft.Practices.Unity;
using UnityExample.Controllers;

namespace UnityExample
{
    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);

            // Create a new Unity dependency injection container
            var unity = new UnityContainer();

            // Register the Controllers that should be injectable
            unity.RegisterType<HomeController>();
            unity.RegisterType<NameController>();

            // Register instances to be used when resolving constructor parameter dependencies
            unity.RegisterInstance(new NameService("It Worked!!!"));

            // Finally, override the default dependency resolver with Unity
            GlobalConfiguration.Configuration.DependencyResolver = new IoCContainer(unity);
        }
    }
}

Step 7 – Now let’s run the app and see that it worked!

Now run the app: Debug -> Start Without Debugging or (Ctrl F5).

When a browser opens, you will see the usual default home page for a .Net MVC 4 Web API application.

Now add the following to your url: /api/name. For example: http://localhost:62283/api/name.

Note: Remember the default path for all ApiControllers in Web API always starts with /api.

You should see the following output:

<string>My name is: It Worked!!!</string>

That is all!

Now that you have a working example, I recommend you read more about how it works in the following article:

Using the Web API Dependency Resolver

Advertisements

12 Comments »

  1. Nice post and very informative.

    Regards,

    European Windows Hosting Provider
    http://www.hostforlife.eu

    Comment by HostForLIFE (@hostforlife) — May 5, 2013 @ 9:29 pm | Reply

  2. This is awesome!! really helpful for me. Thanks for sharing with us. Following links also helped me to complete my task.

    http://www.mindstick.com/Articles/63bce1d2-3d08-48a1-a325-57754b1f000e/?Creating%20a%20simple%20model%20using%20ASP%20NET%20MVC4

    http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-model

    Comment by Royce Roy — June 6, 2013 @ 8:47 am | Reply

  3. Do we need to register Controllers each time? Is there any generic way without do it the same repeatly?

    Comment by oblin — July 25, 2013 @ 8:08 am | Reply

  4. thank you

    Comment by Elvin Arzumanoglu — August 18, 2013 @ 12:34 am | Reply

  5. Wow! Brian, thank you very much for this tutorial, I spent all the morning trying to make it work the DI with WebAPI and only your clean, simple and EFFECTIVE step by step, works like a charm. Thank you very much. Best regards.

    Comment by rubdottocom — April 17, 2014 @ 6:22 am | Reply

  6. Nice Post. For those of you trying this with latest WebApi in VS2013, make sure you use nugget and update all referenced packages & do the same for any Test package(s) you create. Thanks!

    Comment by Loren Lowe — May 1, 2014 @ 4:30 pm | Reply

  7. I have just created a small 30 minutes video which explain DI with Unity application block. https://www.youtube.com/watch?v=FuAhnqSDe-o

    Comment by Shiv — September 2, 2014 @ 12:00 am | Reply

  8. Nice post. I learn something new and challenging on sites I stumbleupon everyday.
    It’s always exciting to read articles from other writers and use a little something from
    their sites.

    Comment by c# Tutorials — October 8, 2014 @ 11:57 pm | Reply

  9. Thanks damienbod for this article, I found below blog post about Unity.Mvc5 Library example with sample code.
    MVC 5 with Unity for Dependency Injection

    Comment by Keith — April 23, 2015 @ 12:23 am | Reply

  10. Reblogged this on avishekrocks.

    Comment by codesnappy — May 26, 2015 @ 4:52 am | Reply

  11. After reviewing a number of other articles/posts wanting to DI a fairly simple controller via Unity, this helped a lot so much appreciated.

    Comment by Phil — September 9, 2016 @ 10:53 am | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: