TypeMapper.cs 1.6 KB

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