Extending interfaces that you don’t control

An example of an interface that you don’t control can be the service client generated by a WCF service reference. If your service contract and operations are defined in an interface, the generated proxy creates the interface and a class generally called <ServiceName>Client. You can make your calls to the service, but if you don’t call the Close method, you’ll find yourself in a faulted state sooner or later.

A simple way to allow you to isolate your dependency on the ClientBase(TChannel).Close Method is to extend the service interface and add the Close method:

public interface IServiceClientBuilder {
    IService Create();
public class ServiceClientBuilder : IServiceClietBuilder {
    public IService Create() {
        return new ServiceClient();
public static class ServiceInterfaceExtensions {
    public static void Close(this IService client)  {
public class MyConsumer {
     IServiceClientBuilder clientBuilder;
     public MyConsumer(IServiceClientBuilder clientBuilder) {
         this.clientBuilder = clientBuilder;
    public void DoSomething() {
        var client = clientBuilder.Create();
        // client.SomeMethod()

This minimizes the "difficult to test" code to only the single-line extension method.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s