Click here to Skip to main content
15,567,466 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:

C#
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:

C#
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
Updated 4-Nov-12 23:10pm
v3

1 solution

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:

C#
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
 
Share this answer
 

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



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