Stevie White
Stevie White

Reputation: 579

How to handle a WCF call per method with lots of methods

I have a DLL that handles making hundreds of method calls either via WCF or directly to QuickBooks. In each method I have code similar to this:

        public Response GetSomethingFromQuickBooks()
    {
        Response response = new Response();

        if (useWCF == true)
        {
            System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();
            System.ServiceModel.EndpointAddress endpoint = new System.ServiceModel.EndpointAddress(new Uri(wcfEndpoint));
            WCFClient = new ServiceReference.OperationsClient(binding, endpoint);
            WCFClient.CreateConnection(opsConnectionDTO);

            response = WCFClient.GetSomethingFromQuickBooks();

            try
            {
                WCFClient.Close();
            }
            catch (Exception)
            {

                WCFClient.Abort();
            }
        }

        else
        {
            response = qbManager.GetSomethingFromQuickBooks();
        }

        return response;
    }

I have a couple of questions:

1) Is this the proper way to handle WCF calls on a per method basis?

2) Is there a way I can instantiate the WCF client on a per method basis without having to put duplicate code in each method?

Upvotes: 1

Views: 67

Answers (1)

tom redfern
tom redfern

Reputation: 31770

Is this the proper way to handle WCF calls on a per method basis?

Well, if we can conveniently ignore fact that you're talking to a service with hundreds of operations defined on it, there are still some things you could be doing differently.

Spinning up a client channel for each call is excessive. Although low, the cost is still significant. It would be better to have some wrapper or factory which could be depended on to manage the lifecycle of the client channel in a sensible way.

Also, it looks like you're using a service reference to call the service. This is sub-optimal for many reasons and should be done only as a last resort, for example when you don't have access to the service interface definition other than via the service metadata. You should be using a WCF Channel otherwise.

Is there a way I can instantiate the WCF client on a per method basis without having to put duplicate code in each method?

Setting aside the fact that client channels are generally reusable as long as they are not faulted, you could utilise an IoC container to inject a runtime dependency containing a freshly-initialised client channel implementation. Either that or reimplement WCFClient as a reusable wrapper around the client channel as mentioned before.

Upvotes: 1

Related Questions