MaiOM
MaiOM

Reputation: 936

MVC 4 and Unity, injecting dependencies to WebAPI controllers

I'm new to MVC and I got stuck on a problem. All the examples I managed to find refer to simple controllers and not to API controllers. Perhaps any one has a working code example on how to, on Application_Start(), register the dependencies to Unity and tweak the code so that once my apicontroller class is created, the right dependency is passed to it. Let's say that this is the definition of my controller:

public class BookController : ApiController
{
    private IBookService bookSerivce;

    public BookController (IBookService bookSerivce)
    {
        this.bookSerivce= bookSerivce;
    }
}

And I expect to register it in unity in the following way:

UnityContainer container = new UnityContainer();

// Register services
container.RegisterType<IBookService , BookService>();

// Register controllers
container.RegisterType<IHttpController, BookController>("Books");

Now, what do I need to do in order to make MVC use unity for resolving the dependencies, start creating instances of this controller and passing the dependencies to it?

I'm using MVC 4. Any idea will be appreciated.

Cheers

Upvotes: 2

Views: 6252

Answers (2)

Sebastian Weber
Sebastian Weber

Reputation: 6806

Mark Seemann has two posts on Dependency Injection with WebAPI.

Dependency Injection and Lifetime Management with ASP.NET Web API

Dependency Injection in ASP.NET Web API with Castle Windsor

If you replace Castle Windsor with Unity the samples should work just the same.

Upvotes: 6

dotarj
dotarj

Reputation: 488

It looks like you are using WebAPI. Check out this post about Unity integration in ASP.NET WebAPI:

Introducing the Unity.WebAPI NuGet Package

Upvotes: 1

Related Questions