Click here to Skip to main content
15,843,623 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Dear all,

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.

Updated 4-Nov-12 23:10pm

1 solution

I found Seemann's post on DI and WebAPI:[^]

Once adapted to use Unity instead of CW, I made it work.

This is my implementation:

public class UnityCompositionRoot : IHttpControllerActivator
    private readonly IUnityContainer container;

    public UnityCompositionRoot(IUnityContainer container)
        this.container = container;

    public IHttpController Create(HttpRequestMessage request, 
        HttpControllerDescriptor controllerDescriptor, Type controllerType)
        var controller = (IHttpController)this.container.Resolve(controllerType);
        return controller;

Then in Global.asax in Application_Start() I did the following:

UnityContainer container = new UnityContainer();
container.RegisterType<IBookService, BookService>();

    new UnityCompositionRoot(container));

Hope it helps.

Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900