JumpStart # 19– Setting up Dependency Injection for ASP.Net Web API

Before looking at the code, Read about – What is JumpStart?

We use Unity IoC container to achieve dependency injection for Web API. Create a ASP.Net MVC4 Project and its associated Class Library as shown in this tutorial – http://www.intstrings.com/ramivemula/articles/dependency-injection-for-multiple-concrete-implementations-of-an-interface/

Instead of installing Unity.Mvc3 Nuget Package, install Unity.WebAPI Nuget Package. Go to Application_Start event in Global.asax and add following code –

Bootstrapper.Initialise();

Go to Bootstrapper.cs and make sure you have following Initialise() method –

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

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

Now add the RegisterTypes as following in BuildUnityContainer() method –

container.RegisterType<IPerson, Male>("Male");
container.RegisterType<IPerson, Female>("Female");

For the sample implementation, we go for default Values Controller and change it code to –

    public class ValuesController : ApiController
    {
        private IPerson malePerson;
        private IPerson femalePerson;

        public ValuesController([Dependency("Male")]IPerson malePerson, [Dependency("Female")]IPerson femalePerson)
        {
            this.malePerson = malePerson;
            this.femalePerson = femalePerson;
        }

        public Person Get()
        {
            return malePerson.GetPerson();
        }
    }

When we run the project from VS 2012 and use fiddler to check the output, we get following –

 

WebDI1

 

TIP: To get both MVC and Web API Dependency injection going on in the same project, you need to have both –

1. Unity.Mvc3 – Follow this

2. Unity.WebAPI – Present tutorial

That’s it for now, let me again later with different constructor injections.

You may also like...

2 Pingbacks/Trackbacks