Search code examples
c#wcfservice-reference

Object instances in static classes


I am developing a web application with multiple WCF service references. Currently, each time we need to make a call to a service we do the following(as an example):

Service.ServiceClient ServiceClient = new Service.ServiceClient();
ServiceClient.SomeMethod();

Would it be better to have a static class with static references to each Service and call that class instead, thereby avoiding creating a new instance of the ServiceClient object each time we want to call it?

For example:

public static class Services
{
    private static Service.ServiceClient _ServiceClient = new Service.ServiceClient();
    public Service.ServiceClient ServiceClient
    {
        get
        {
            return _ServiceClient;
        }
    }
}

And, if doing it this way, would the line

private static Service.ServiceClient _ServiceClient = new Service.ServiceClient();

cause a new object to be created each time we try to call that object, or will it be the same instance of that object every time we make a call to it?


Solution

  • You can have a class which will have all the functions exposed by your data contract. All these methods will be static. Now inside these function you can do as follows

    public class ServiceManager{
        public static CalculatedData SomeMethod()
        {
             var client = GetClient();
             try
             {
                 return client.SomeMethod();
             }
             catch(Exception ex)
             {
                 //Handle Error
             }
             finally
             {
                 if(client.State == System.ServiceModel.CommunicationState.Opened)
                    client.Close();
             } 
    
        }
        private static SomeClient GetClient()
        {
             return new ServiceClient();
        }
    } 
    

    Consumer will consume it like

    var calculatedData = ServiceManager.SomeMethod();