Click here to Skip to main content
Rate this: bad
good
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.
 
Cheers
Posted 4-Nov-12 10:30am
Edited 4-Nov-12 22:10pm
v3

1 solution

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

Solution 1

I found Seemann's post on DI and WebAPI:
http://blog.ploeh.dk/2012/10/03/DependencyInjectionInASPNETWebAPIWithCastleWindsor.aspx[^]
 
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>();
 
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), 
    new UnityCompositionRoot(container));
 
Hope it helps.
 
Cheers
  Permalink  

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



Advertise | Privacy | Mobile
Web04 | 2.8.140926.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