I have a class that takes a dependency on a WCF client proxy, the default one generated by Add Service Reference in VS 2010. We’re set up to use StructureMap for Dependency Injection, and the generator also generates an interface. Cool. Wire it up in the StructureMap initialization and use some constructor injection, new’d up client available in my class. And it seems to work great.

And then I start firing up some load tests, calling the WCF service lots of times (like 50 or so). The tests hang up after 10. Stack Overflow reveals that’s the default # of open connections a WCF service allows to a particular client.

OK, so I need to start closing the connections opened by client proxies. But this class of mine, it has several methods that interact with the service. I’m not sure if I’m really done with it after any given call.

Well, I can be sure if I can new up the client proxy in each of my class’ methods, and close it after I’m done, right? How will I make that work without actually calling new? I mean, I want to be able to mock it out in unit tests, right?

Here’s what I came up with. ExpensiveService is the WCF client proxy, TheService is the class under test (the one I’m writing). What do you think?

public class ExpensiveService : IDisposable
{
    public virtual void DoSomethingExpensive()
    {
        Console.WriteLine("Thread.Sleep(5000)");
        System.Threading.Thread.Sleep(5000);
    }

    public void Dispose() { }
}
public class TheService
{
    public Func<ExpensiveService> GetExpensiveService { get; set; }

    public TheService()
    {
        // The default implementation.

        this.GetExpensiveService = () => new ExpensiveService();
    }

    public void TestMethod()
    {
        using (var expensiveService = GetExpensiveService())
        {
            expensiveService.DoSomethingExpensive();
        }
    }
}
[TestFixture]
public class TheServiceTest
{
    [Test]
    public void CanStubExpensiveService()
    {
        var theService = new TheService();
        theService.GetExpensiveService = () => new StubExpensiveService();
        theService.TestMethod();
    }

    private class StubExpensiveService : ExpensiveService
    {
        public override void DoSomethingExpensive()
        {
            Console.WriteLine("No sleeping here");
        }
    }
}