2
0

TypeMapper.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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
  13. /// so that we can de-serialize properly when we don't have strong types.
  14. /// </summary>
  15. private readonly ConcurrentDictionary<string, Type> _typeMap = new ConcurrentDictionary<string, Type>();
  16. /// <summary>
  17. /// Gets the type.
  18. /// </summary>
  19. /// <param name="typeName">Name of the type.</param>
  20. /// <returns>Type.</returns>
  21. /// <exception cref="ArgumentNullException"><c>typeName</c> is null.</exception>
  22. public Type GetType(string typeName)
  23. {
  24. if (string.IsNullOrEmpty(typeName))
  25. {
  26. throw new ArgumentNullException(nameof(typeName));
  27. }
  28. return _typeMap.GetOrAdd(typeName, LookupType);
  29. }
  30. /// <summary>
  31. /// Lookups the type.
  32. /// </summary>
  33. /// <param name="typeName">Name of the type.</param>
  34. /// <returns>Type.</returns>
  35. private Type LookupType(string typeName)
  36. {
  37. return AppDomain.CurrentDomain.GetAssemblies()
  38. .Select(a => a.GetType(typeName))
  39. .FirstOrDefault(t => t != null);
  40. }
  41. }
  42. }