Is it correct to implement IDisposable on Singleton

In our WCF project we are using singleton pattern

to get the client proxy.

Mainly because -

  • Any improvements that are needed later, when adding a client object Binding

    or Endpoint

    , will require minimal changes.
  • We do not call multiple services at the same time.

To make sure it is connection is closed

correct after each service call, we plan to implement IDisposable

in singleton as shown below -

public class ClientSingleton : IDisposable
{
    static Service1Client client;
    private ClientSingleton()
    {
        client = new Service1Client();
    }
    public Service1Client getInstance()
    {
        if (client != null)
            return client;
        else
        {
            client = new Service1Client();
            return client;
        }
    }
    public void Dispose()
    {
        client.Close();
    }
}

      

Does this violate Singleton principles Design-Pattern

? Any advice on how to improve this would be helpful.

change

Consider using block

placing a client facility as below:

using (Service1Client client = new Service1Client())
{
    client.Operation1();
}

      

This means that WCF proxies implement the interface IDisposable

. So I see no harm in implementing this interface here.

Thank!

+1


source to share


1 answer


I am using an extension method in my project that takes care of closing the service connection properly. (I stole an extension method from some blog and I forgot this blog link)

public static void CloseConnection(this ICommunicationObject client)
{
  if (client.State != CommunicationState.Opened)
  {
    return;
  }

  try
  {
    client.Close();
  }
  catch (CommunicationException)
  {
    client.Abort();
    throw;
  }
  catch (TimeoutException)
  {
    client.Abort();
    throw;
  }
  catch (Exception)
  {
    client.Abort();
    throw;
  }
}

      

Unlike your approach (which is proxy specific) this can be used for any proxy to securely close the connection.



Usage example

Service1Client client = null

try
{
  client = new Service1Client();
}
finally
{
  if(client != null)
     client.CloseConnection();
}

      

+1


source







All Articles