Search code examples
c#design-patternssingletonhttpconnection

Pattern for Single Connection in C#


We would like to use single instance of Http Connection to communicate to server as it's guaranteed to communicate to one end http endpoint

Ex:

MyConnection.GetRoute<ABC>.DoStuff()   --https://user.site.com/abc/
MyConnection.GetRoute<XYZ>.DoStuff()   --https://user.site.com/xyz/

From the design patterns, Singleton seems to make perfect case

public class MyConnectionHelper
{
   private static MyConnection instance;

   private MyConnectionHelper() {}

   public static MyConnectionHelper Instance
   {
       get{
         if(instance == null){
            instance = new MyConnection();
         }
         return instance;
       }
   }
}

But we need some credentials to make connection and proxy information to be used if required, these properties should be exposed

public class MyConnectionHelper
{
   public static string authKey;
   public static string proxyUrl;
   private static MyConnection instance;

   private MyConnectionHelper() {}

   public static MyConnectionHelper Instance
   {
       get{
         if(instance == null) {
            instance = new MyConnection(proxyUrl, authKey);
         }
         return instance;
       }
   }
}

Is there any better design pattern suits for this use case and better way to expose required/optional parameters that can be provided before creating the connection and reuse it through out the cycle.


Solution

  • You could use something like the code below. When you set the credentials, it flags the connection to be reset. When you access the connection for the first time after that, it will recreate the connection.

    private static bool resetConnection;
    
    private static string authKey;
    private static string proxyUrl;
    
    public static string AuthKey
    {
        get => authKey;
        set
        {
           authKey = value;
           resetConnection = true;
        }
    }
    
    public static string ProxyUrl
    {
        get => proxyUrl;
        set
        {
           proxyUrl = value;
           resetConnection = true;
        }
    }
    
    public static MyConnection HelperInstance
    {
        get
        {
            if(resetConnection == null)
            {
                instance = new MyConnection(proxyUrl, authKey);
                resetConnection = false;
            }
    
            if(instance == null)
            {
                instance = new MyConnection(proxyUrl, authKey);
                resetConnection = false;
            }
    
            return instance;
        }
    }