GAT
GAT

Reputation: 115

Need a way to close a ChannelFactory when the client only know of the interface

please help me solve this issue.

I have a client using WCF. I don't want this client to know that it gets its data from a service. I want to use a model like this so I it easier for me to unit test the code and to later replace the implementation of the given interface. The problem with this model is that I'm not able to call close on the ChannelFactory. I'm not sure that I need to call close, but it feels right.

So my question is:

Does anybody know of a good pattern for closing the ChannelFactory when the client only should know the interface of the service? Or is the ChannelFactory closed by it self by some kind of magic?

Below is some sample code that I hope will you understand the question:

    static void Main(string[] args)
    {
        ITestService service = GetTestService();
        Console.WriteLine(service.GetData(42));

    }

    private static ITestService GetTestService()
    {
        var cf = new ChannelFactory<ITestService>(new WSHttpBinding(), new EndpointAddress("http://localhost:8731/TestService/"));
        return cf.CreateChannel();
    }

Thanks, GAT

Upvotes: 2

Views: 3187

Answers (3)

RichardOD
RichardOD

Reputation: 29157

Have you tried casting it to a IClientChannel and then calling Close?

((IClientChannel)service).Close();

Upvotes: 1

Vitaliy Liptchinsky
Vitaliy Liptchinsky

Reputation: 5299

You should implement class like

public class MyClient : ITestService 
{
private ChannelFactory<ITestService> factory;
private ITestService proxy;
//...
//expose here methods Open and Close that internally will open and close channel factory
//implement interface members
}

The lifetime of the client here will be the same as lifetime of channel factory.

Upvotes: 2

Ronald Wildenberg
Ronald Wildenberg

Reputation: 32104

The best way to solve this is to keep the reference to the ChannelFactory alive for as long as you need it. So take the creation of the ChannelFactory out of the GetTestService method and create the factory on initialization of your class (in the constructor for example) and close it when you no longer need the factory (in the Dispose method of your class for example).

ChannelFactory is a factory class that you can reuse as many times as you like, so there is no need to create it each time you need a service implementation.

Upvotes: 4

Related Questions