TypeMapper.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Linq;
  4. namespace Emby.Server.Implementations.Data
  5. {
  6. /// <summary>
  7. /// Class TypeMapper
  8. /// </summary>
  9. public class TypeMapper
  10. {
  11. /// <summary>
  12. /// This holds all the types in the running assemblies so that we can de-serialize properly when we don't have strong types
  13. /// </summary>
  14. private readonly ConcurrentDictionary<string, Type> _typeMap = new ConcurrentDictionary<string, Type>();
  15. public TypeMapper()
  16. {
  17. }
  18. /// <summary>
  19. /// Gets the type.
  20. /// </summary>
  21. /// <param name="typeName">Name of the type.</param>
  22. /// <returns>Type.</returns>
  23. /// <exception cref="ArgumentNullException"></exception>
  24. public Type GetType(string typeName)
  25. {
  26. if (string.IsNullOrEmpty(typeName))
  27. {
  28. throw new ArgumentNullException(nameof(typeName));
  29. }
  30. return _typeMap.GetOrAdd(typeName, LookupType);
  31. }
  32. /// <summary>
  33. /// Lookups the type.
  34. /// </summary>
  35. /// <param name="typeName">Name of the type.</param>
  36. /// <returns>Type.</returns>
  37. private Type LookupType(string typeName)
  38. {
  39. return AppDomain.CurrentDomain.GetAssemblies()
  40. .Select(a => a.GetType(typeName))
  41. .FirstOrDefault(t => t != null);
  42. }
  43. }
  44. }