简体   繁体   中英

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?

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

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

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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM