Click here to Skip to main content
13,141,576 members (53,812 online)
Rate this:
Please Sign up or sign in to 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.

Posted 4-Nov-12 10:30am
Updated 4-Nov-12 22:10pm

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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.


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

Advertise | Privacy |
Web01 | 2.8.170915.1 | Last Updated 5 Nov 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100