0

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;
    }
}
Riley Christian
  • 149
  • 1
  • 13
  • 1
    When you add a `new()` constraint to a class, you are constraining the class to be one that has a default constructor. As a result, you can use the default constructor in your code. You appear to be trying to use a one parameter constructor (passing in a parameter named `param` that doesn't appear anywhere else in your code). You should have two errors - one about `param` and the other about invoking a non-default constructor – Flydog57 Jun 04 '21 at 15:51
  • Could you please share some snippets ? – Riley Christian Jun 04 '21 at 16:36
  • What is the point of `param`. It occurs only once in your code (in the `T` constructor). Where is is supposed to come from? – Flydog57 Jun 04 '21 at 17:02

0 Answers0