Click here to Skip to main content
Rate this: bad
Please Sign up or sign in to vote.
See more: MVC DI webapi Unity
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
Edited 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
0 Dnyaneshwar@Pune 604
1 OriginalGriff 394
2 thatraja 370
3 Sergey Alexandrovich Kryukov 329
4 CPallini 179
0 OriginalGriff 697
1 Dnyaneshwar@Pune 604
2 Kornfeld Eliyahu Peter 495
3 thatraja 370
4 Sergey Alexandrovich Kryukov 344

Advertise | Privacy | Mobile
Web03 | 2.8.140827.1 | Last Updated 5 Nov 2012
Copyright © CodeProject, 1999-2014
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