Saturday 21 January 2012

WCF Web API Dependency Injection using Spring.Net

It has been a while.... :-)

I am currently working on a side project to implement a catalogue service using RavenDB on Windows Azure. For various reasons, I decided to hide RavenDB behind a WCF Rest Service.

I am also using Spring.NET, and whilst there is documentation on using Spring.NET with WCF, the configuration required seems to differ slightly when using WCF and Web API. All I needed was a hook in Web API to instantiate my service class when required.

Luckily, Web API does have one. The code below shows you an extended host factory which will set the http configuration class delegates. Note here that those delegates are only to instantiate the class in the first place. Any other manipulation of this class instance are handled by the Web API framework (ergo, any decorated contract class attributes will still be processed as normal).

The new service host factory looks like this:



To use this host factory, simply replace the one defined in your route by the one above:



Define your spring configuration as the one you would use for a web form application in your web.config, and that's it. All you need is to define your contract service class in spring, and as long as the id is the same as your class name, the service class used for the request will be instantiated by spring.