2

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

1
  • So you are using Web API or MVC? Commented Nov 5, 2012 at 3:44

2 Answers 2

6

Mark Seemann has two posts on Dependency Injection with WebAPI.

Dependency Injection and Lifetime Management with ASP.NET Web API

Dependency Injection in ASP.NET Web API with Castle Windsor

If you replace Castle Windsor with Unity the samples should work just the same.

Sign up to request clarification or add additional context in comments.

3 Comments

I saw Seemann's post but unfortunately I was too quick on discarding it. I checked it better and adapted the code to use Unity instead of CW and it works like a charm! Thanks
Links don't exist anymore.
@MattSpradley Fixed broken links
1

It looks like you are using WebAPI. Check out this post about Unity integration in ASP.NET WebAPI:

Introducing the Unity.WebAPI NuGet Package

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.