Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the lazily-initialize type does not have a public parameter-less constructor

I am trying to implement an example in youtube, the tutor got it right but I got an error.
I already have a private constructor and I cannot have public constructor in my code.

private static int _InstanceCount = 0;

private SingletonDemo1()
{
    _InstanceCount++;
    Console.WriteLine("Instance Count: " + _InstanceCount.ToString());
}

private static readonly Lazy<SingletonDemo1> _Instance = new Lazy<SingletonDemo1>();

public static SingletonDemo1 Instance
{
    get
    {                               
        return _Instance.Value;
    }
}
like image 352
Developer Avatar asked Oct 16 '17 05:10

Developer


1 Answers

According to the example you need to manually initialize the object in the constructor of the Lazy just like in the demo video

private static readonly Lazy<SingletonDemo1> _Instance = new Lazy<SingletonDemo1>(() => new SingletonDemo1());

Note the factory function used.

Without it the code would try to use reflection to initialize the object but as you have already stated the constructor is private so it will fail. That is why you need to tell the Lazy how to create the instance when needed.

like image 55
Nkosi Avatar answered Sep 27 '22 18:09

Nkosi