How to create a common Singleton base class C #

I am trying to create a common singleton base class like

public class SingletonBase<T> where T : class, new()
{
    private static object lockingObject = new object();
    private static T singleTonObject;
    protected SingletonBase()
    {

    }

    public static T Instance
    {
        get
        {
            return InstanceCreation();
        }
    }
    public static T InstanceCreation()
    {
        if(singleTonObject == null)
        {
             lock (lockingObject)
             {
                  if(singleTonObject == null)
                  {
                       singleTonObject = new T();
                  }
             }
        }
        return singleTonObject;
    }
}

But I have to make the constructor publicly available in the derived.

public class Test : SingletonBase<Test>
{
    public void A()
    {

    }
    private Test()
        : base()
    { }
}

Compilation Error:

A "test" must be a non-abstract type with an open constructor without parameters in order to use it as a "T" parameter in a general "Test" type or method

How can i achieve this?

+5
source share
2 answers

The problem is your general limitation where T : class, new(). The constraint new()requires a public constructor with no parameters on T. There is no way around this; you need to provide such a constructor in Permission Controller.

+6
source

. .

, SingletonBase<T>. , SingletonBase<T> .

public static class Singleton<T> where T : class, new()
{
    ...
}

var test = Singleton<Test>.Instance;

Test ,

public class Test 
{
    public static T Instance
    {
        get { return Singleton.Instance<Test>; }
    }
}
+3

All Articles