How to get an instance from a singleton class with reflection

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?

+4
source share
3 answers

To create an instance, do the same as in the code - get the value Instance :

 var singleton = typeof(Test).GetProperty("Instance").GetValue(null); 
+5
source

To do this, you must pass the appropriate GetProperty () flags:

 var property = strtegy.GetProperty("Instance", BindingFlags.Public | BindingFlags.Static); var instance = property.GetValue(null); 
+3
source

You do not need to use a constructor, just get access to this property.

 var value = typeof (Test).GetProperty("Instance").GetValue(null, null); 
+1
source

Source: https://habr.com/ru/post/1493129/


All Articles