Need a way to close the ChannelFactory when the client is aware of the interface

please help me to solve this problem.

I have a client using WCF. I don't want this client to know that he is getting his data from the service. I want to use such a model to make it easier for me to unit test the code and later replace the implementation of this interface. The problem with this model is that I cannot call the ChannelFactory. I'm not sure if I need to call close, but it feels good.

So my question is:

Does anyone know of a good pattern for closing a ChannelFactory when the client needs to know the interface of that service? Or is the Canadian Foundation closed by itself through some kind of magic?

Below is some sample code that I hope 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

+2


source to share


3 answers


The best way to solve this problem is to keep the link ChannelFactory

alive for as long as you need it. So create ChannelFactory

from a method GetTestService

and create a factory when you initialize your class (e.g. in a constructor) and close it when you no longer need the factory (in a Dispose

method of your class, for example).



ChannelFactory

is a factory class that can be reused as many times as you like, so there is no need to create it every time you need a service implementation.

+4


source


You have to implement a 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 client lifetime here will be the same as the factory channel lifetime.

+2


source


Have you tried sending it to IClientChannel and then calling Close?

((IClientChannel)service).Close();

      

+1


source







All Articles