asp.netweb-servicesdependency-injectioninversion-of-control

How to use dependency injection and the repository pattern with ASP.NET web services?


With regular ASP.NET MVC pages, the repository is passed in to the constructor of the control. Then the tests can instantiate the controller passing in a mock repository.

How can I do this with web services? The problem I see is that we don't have the equivalent of ControllerBuilder.SetControllerFactory.

What are the best practices to get my IoC framework (Castle) to instantiate my web service with the correct repository implementation?

I thought there might be a way to extend HttpHandler and change the way the web service is actually instantiated. I believe this is how the MVC framework does it.


Solution

  • I believe you are looking for the Castle Windsor WCF Integration Facility. It provides a ServiceHost implementation that takes over the construction process of your service implementations, utilizing the Windsor IOC. You can inject dependencies like any other IoC app using this facility, and conveniently enough, its part of the Castle project:

    http://www.castleproject.org/container/facilities/trunk/wcf/index.html

    If the Castle Project version does not do what you need it to do, I have my own facility that I created to do the same thing for Windsor before I found the Castle project's version. They both generally do the same thing, but both also approach the problem a little differently.