vendredi 4 juin 2021

Refactoring a singleton class into a base generic class

I two singleton classes that shares exactly the implementation except that differ on types of objects. Because i know in the future i will keep adding more singleton types with same implementation i thought it would be a good idea to refactor the singleton class into generic base class. However i have errors on like shown in the snippets below and i don't know how to implement a singleton into a base generic class.

public class BaseClass<T> where T: new()
{
   //Singleton instance 
   protected static readonly Lazy<T> _instance = new Lazy<T>(() => new T (param)); //Error on new T
   protected static SqlTableDependency<TableC> tableDependency;

   //Constructor
   private T(IHubConnectionContext<dynamic> clients)
   {
       Clients = clients;

        _tableDependency = new SqlTableDependency<TableC>(
            ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString, "TableC");
   }
   //Properties
   public static T Instance
   {
        get
        {
            return _instance.Value;
        }
    }

    private IHubConnectionContext<dynamic> Clients
    {
        get;
        set;
    }
}

Aucun commentaire:

Enregistrer un commentaire