views:

39

answers:

1

Usually I have client code similiar to something like this:

// SomeOtherServiceClient would be injected in actual code.
ISomeOtherService client = new SomeOtherServiceClient();

... so that I can mock the service for testing. But now I have a WCF service that has the context mode set to PerSession and implements IDisposable.

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class SampleService : ISampleService, IDisposable
{
    public void SampleMethod() { ... }
    public void Dispose() { ... }
}

If I wish to put the client inside a using statement, is there still a way for me to mock the client for testing?

// SampleServiceClient would be injected in actual code.
using (var client = new SampleServiceClient())
{
    ...
}
+1  A: 

If I understand the problem, it is that ISomeOtherService is a WCF service contract, and does not implement IDisposable even though all implementing clients will. You can get around this by changing the using statement to something like this:

public void SampleMethod()
{
    //client was injected somehow
    using(this.client as IDisposable)
    {
        ...
    }
}
Lee
This does not solve the issue mentioned by Andrew above, the dispose method will throw an exception on a faulted channel. Use Juval`s method for safely closing proxies.
MetalLemon