views:

185

answers:

3

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();
    }
}
A: 

Should you decide to go with a member, please keep in mind that once it gets faulted, all calls afterwards will fail. As for whether it's worth it, I suggest benchmarking.

Steven Sudit
+1  A: 

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

marc_s
+1  A: 

In the past, I've created a new instance of the ChannelFactory<> and client/proxy for every call to the WCF service. I haven't had any problems with it, especially not for performance. The application I wrote was deployed on an internal company network (local LAN) where about 30 Windows Forms clients would connect to my WCF service.

Have a look at the following question http://stackoverflow.com/questions/1204534/where-to-trap-failed-connection-on-wcf-calling-class/1243889#1243889 and my answer to it. Its basically a wrapper class which handles client/proxy instantiation and does a lot of necessary error handling to overcome certain shortcomings in the design of WCF (more info in the linked question).

You could re-write it or wrap it further in another factory, so that you can cache the ChannelFactory and client/proxy if you are worried about performance. I have "heard" that its a bad idea to cache the ChannelFactory or client/proxy - however, I am open to correction here.

Saajid Ismail