ConstructorCache.cs 950 B

1234567891011121314151617181920212223242526272829303132
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Linq;
  4. using System.Reflection;
  5. namespace OpenSEMI.Core.Container
  6. {
  7. internal class ConstructorCache
  8. {
  9. private static ConcurrentDictionary<Type, ConstructorInfo> _constructorCache = new ConcurrentDictionary<Type, ConstructorInfo>();
  10. public static ConstructorInfo GetConstructor(Type type)
  11. {
  12. ConstructorInfo constructor;
  13. if (!_constructorCache.TryGetValue(type, out constructor))
  14. constructor = _constructorCache[type] = DiscoverConstructor(type.GetTypeInfo());
  15. return constructor;
  16. }
  17. private static ConstructorInfo DiscoverConstructor(TypeInfo typeInfo)
  18. {
  19. var constructors = typeInfo.DeclaredConstructors;
  20. if (constructors.Any())
  21. return constructors.First();
  22. return null;
  23. }
  24. }
  25. }