Dependency Injection wcf

When you use svcutil.exe or the Add Service Reference wizard in Visual Studio, one of the many types auto-generated will be a client interface. Let’s call it IMyService. There will also be another auto-generated interface called something like IMyServiceChannel that implements IMyService and IDisposable. Use this abstraction in the rest of your client application.

Since you want to be able to create a new channel and close it again, you can introduce an Abstract Factory:

public interface IMyServiceFactory
{
    IMyServiceChannel CreateChannel();
}

In the rest of your client application, you can take a dependency on IMyServiceFactory:

public class MyClient
{
    private readonly IMyServiceFactory factory;

    public MyClient(IMyServiceFactory factory)
    {
        if (factory == null)
        {
            throw new ArgumentNullException("factory");
        }

        this.factory = factory;
    }

    // Use the WCF proxy
    public string Foo(string bar)
    {
        using(var proxy = this.factory.CreateChannel())
        {
            return proxy.Foo(bar);
        }
    }
}

You can create a concrete implementation of IMyServiceFactory that wraps WCF’s ChannelFactory<T> as an implementation:

public MyServiceFactory : IMyServiceFactory
{
    public IMServiceChannel CreateChannel()
    {
        return new ChannelFactory<IMyServiceChannel>().CreateChannel();
    }
}

You can now configure your DI Container by mapping IMyServiceFactory to MyServiceFactory. Here’s how it’s done in Castle Windsor:

container.Register(Component
    .For<IMyServiceFactory>()
    .ImplementedBy<MyServiceFactory>());

Bonus info: Here’s how to wire up a WCF service with a DI Container.

Leave a Comment