Consider this code:
public class Test { private static readonly Lazy<Test> Lazy = new Lazy<Test>(() => new Test()); private Test() { Console.WriteLine("Calling constractor"); } public static Test Instance { get { return Lazy.Value; } } public void Something() { } }
When I want to create an instance from the class above, we must change the access modifier of the constructor to public, and to get an instance from this class I will write this code:
Type type = typeof(Test); IEnumerable<Type> types = AppDomain.CurrentDomain.GetAssemblies().ToList() .SelectMany(s => s.GetTypes()) .Where(type.IsAssignableFrom); Type strtegy = types.FirstOrDefault(x => x.IsClass); for (int i = 0; i < 10; i++) { Activator.CreateInstance(strtegy); }
If this code is used for every call that calls the Activator.CreateInstance constructor. So we have many instances of the class.
How to get an instance from a singleton class with reflection?
source share