Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF Client Instantiation

I have a mvc controller class that uses a WCF service(WSHttpBinding), sometimes multiple calls within one http request, and want to know how expensive it is to create a client for that service. Is it ok to create an instance of the client for every call or should I create a member variable in the class?

public class RingbacksController : Controller
{
    private void LoadContactsIntoViewData(int page)
    {
                RingbackServiceClient client = new RingbackServiceClient();
        ...
        client.Close();
    }

    private void LoadGroupsIntoViewData(int page)
    {
                RingbackServiceClient client = new RingbackServiceClient();
        ...
        client.Close();
    }
}

or

public class RingbacksController : Controller
{
    private RingbackServiceClient client = new RingbackServiceClient();

    private void LoadContactsIntoViewData(int page)
        {
        ...
        client.Close();
    }

    private void LoadGroupsIntoViewData(int page)
    {
        ...
        client.Close();
    }
}
like image 774
Nick Avatar asked Jul 30 '09 16:07

Nick


1 Answers

Creating the client is usually not an awful expensive operation - so you should be fine instantiating it whenever you need it (as Steven mentioned, too - if it's faulted due to an error, you'll need to do that anyway).

Should you be using a ChannelFactory to create the channel (that's one of the ways to do it), creating the ChannelFactory on the other hand is a pretty heavyweight and time-intensive operation, so it would be a good idea to hang on to a ChannelFactory instance for as long as you can.

Marc

like image 127
marc_s Avatar answered Oct 08 '22 17:10

marc_s