Asdfg
Asdfg

Reputation: 12253

how do i close wcf client

In my business layer, i am using WCF service. WCF service instance can be passed in the constructor as well. Here are the constructors of my BL.

    private IWCFClient wcfClient;

    public MyBL()
        :this(new WCFClient())
    {

    }

    public MyBL(IWCFClient wcfClient)
    {
        serviceClient = wcfClient;
    }

because i am declaring my wcfClient as an interface, i dont get .Close() method there. I have to typecast it to close it as ((RealwCFClient)wcfClient).Close();

Is there a way i can close my client without typecasting it? Should i expose a Close method in my interface?

Upvotes: 2

Views: 1450

Answers (5)

BellBat
BellBat

Reputation: 145

Here is a link to MSDN doc concerning closing a client.

Generally speaking dispose/close is not expected to throw an exception I use an extension method that encapsuates this functionality, here is a pretty good article providing the basic concept.

I like the verbs Use or Execute for the method name as opposed to Using, since using has the connotation of calling dispose which most people do not expect exceptions from.

Upvotes: 1

Dan Waterbly
Dan Waterbly

Reputation: 850

You may implement IDisposable for your class and in your Dispose method close the WCF service instance.

public class Consumer
{
    public void SomeMethod()
    {
        using (WCFClient client = new WCFClient(new WCFService()))
        {
            int sum = client.Add(5, 10);
        }
    }
}

public class WCFClient : IDisposable
{
    private WCFService _service;

    public WCFClient(WCFService service)
    {
        _service = service;
    }

    public int Add(int a, int b)
    {
        return _service.Add(a, b);
    }

    public void Dispose()
    {
        if (_service != null)
            _service.Close();
    }
}

The using block in the Consumer's SomeMethod() method will ensure that the WCFClient's dispose method will be called closing the connection to the service.

Upvotes: 1

BrandonZeider
BrandonZeider

Reputation: 8152

In addition to the other answers, you should also consider creating a reusable WCF service client. In this reusable client, you can handle the open and close, and not make the consuming class worry about it.

Upvotes: 1

Maxim
Maxim

Reputation: 7348

Cast your object to ICommunicationObject and then .Close() it.

Note that Close() can throw an exception, in this case catch it and do .Abort()

Upvotes: 3

Justin Niessner
Justin Niessner

Reputation: 245489

As long as all concrete implementers of IWCFClient will have a Close() method, then add the Close() method to the interface.

Upvotes: 0

Related Questions