You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LuConvertersAllocator.cs 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using Luticate2.Auth.Utils.Dbo;
  5. using Luticate2.Auth.Utils.Dbo.Result;
  6. using Luticate2.Auth.Utils.Interfaces;
  7. namespace Luticate2.Auth.Utils.Business.Converters
  8. {
  9. public class LuConvertersAllocator : ILuConvertersAllocator
  10. {
  11. protected static IDictionary<Type, Type> listTypes = new Dictionary<Type, Type>
  12. {
  13. {typeof(IEnumerable<>), typeof(List<>)},
  14. {typeof(ICollection<>), typeof(Collection<>)},
  15. {typeof(Collection<>), typeof(Collection<>)},
  16. {typeof(IList<>), typeof(List<>)},
  17. {typeof(List<>), typeof(List<>)}
  18. };
  19. public virtual LuResult<object> CreateInstance(Type type)
  20. {
  21. try
  22. {
  23. var obj = Activator.CreateInstance(type);
  24. // TODO Nullable<T> (and maybe others) gets null instead of object
  25. // if (obj != null)
  26. // {
  27. return LuResult<object>.Ok(obj);
  28. // }
  29. // return LuResult<object>.Error(LuStatus.InternalError.ToInt(),
  30. // $"Could not instantiate type {type}");
  31. }
  32. catch (Exception e)
  33. {
  34. return LuResult<object>.Error(LuStatus.InternalError.ToInt(), e);
  35. }
  36. }
  37. public virtual LuResult<object> GetInstance(Type type)
  38. {
  39. if (type.IsGenericType)
  40. {
  41. var gtype = type.GetGenericTypeDefinition();
  42. if (listTypes.ContainsKey(gtype))
  43. {
  44. var glistType = listTypes[gtype].MakeGenericType(type.GenericTypeArguments[0]);
  45. var listActivateResult = CreateInstance(glistType);
  46. return listActivateResult;
  47. }
  48. }
  49. if (type == typeof(string))
  50. {
  51. return LuResult<object>.Ok("");
  52. }
  53. var activateResult = CreateInstance(type);
  54. return activateResult;
  55. }
  56. }
  57. }