This is a mirror of official site: http://jasper-net.blogspot.com/

Improve WCF services testability with simple Dependency Injection

| Wednesday, February 1, 2012
Dependency injection is a great technique to reduce coupling between components and improve testability. There are few techniques we can create dependency injections, you can use a framework like MEF or spring to Automate dependency injection but I personally favor manually injected dependencies. call me old fashion, but I like creating object via simple constructor calls (most of the time).

This is really straight forward most of the time but when dealing with WCF services there is a slight complexity to take in to consideration. In most scenarios WCF is in charge of instantiating the service class (the only exception here is with single instance context mode, where we can supply ServiceHost with a ready made instance of our service class).

Lately I have come across a really cool (and simple) option in WCF Web API. The WCF Web API supply an HttpConfiguration API that exposes a CreateInstance delegate we can use to manually create a new instance of our service class:
HttpConfiguration config = new HttpConfiguration();
config.CreateInstance = (type, context, message) =>
{
    IPlayersDal dal = new PlayersDal();
    return new PlayersCURD(dal);
};

var factory = new HttpServiceHostFactory() { Configuration = config };

While this API is cool, it can only be used for http based services (using the WCF Web API). I really felt like using something like that in a SOAP based project I am currently working on so I figured what the hack, I can create the similar solution (source code can be found here) for any WCF service host out there.

The first stop was creating an IExtension<ServiceHostBase> that can transport the delegate down the WCF pipeline:
class InstanceInitializerExtension : IExtension<ServiceHostBase>
{
    public Func<object> InstanceInitializer;

    public void Attach(ServiceHostBase owner)
    {
    }

    public void Detach(ServiceHostBase owner)
    {
    }
}


Read more: I'm on a mission from God object
QR: improve-wcf-services-testability-with-simple-dependency-injection.aspx

Posted via email from Jasper-net

0 comments: