Mapper.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using Quadarax.Foundation.Core.Data.Interface.Entity;
  3. using Quadarax.Foundation.Core.Mapper;
  4. namespace Quadarax.Foundation.Core.Data.Mapper
  5. {
  6. public class Mapper<TMapper> : Loom where TMapper : class, new()
  7. {
  8. /// <summary>
  9. /// Singleton instance of this class.
  10. /// </summary>
  11. public static TMapper Instance => _instance.Value;
  12. private static readonly Lazy<TMapper> _instance = new Lazy<TMapper>(() => new TMapper());
  13. #region ------ Constructors ---------------------------------------------------------------
  14. /// <summary>
  15. /// Initializes a new instance of this class.
  16. /// </summary>
  17. public Mapper()
  18. {
  19. }
  20. /// <summary>
  21. /// Defines mappings from a DAO to DTO and vice-versa.
  22. /// </summary>
  23. /// <typeparam name="TDao"></typeparam>
  24. /// <typeparam name="TDto"></typeparam>
  25. protected void DefineBiDirection<TDao, TDto, TKey>()
  26. where TDao : class, IDao<TKey>, new()
  27. where TDto : class, IDto, new()
  28. where TKey : IEquatable<TKey>
  29. {
  30. Define<TDao, TDto>()
  31. .PublicProperties()
  32. .Compile();
  33. Define<TDto, TDao>()
  34. .PublicProperties()
  35. .Compile();
  36. }
  37. protected void Define<TDao, TDto>(Action<LoomBuilder<TDao, TDto>> customFromDao)
  38. where TDao : class, IDao<long>, new()
  39. where TDto : class, IDto, new()
  40. {
  41. // from DAO to DTo
  42. var builder = Define<TDao, TDto>();
  43. builder.PublicProperties();
  44. customFromDao?.Invoke(builder);
  45. builder.Compile();
  46. }
  47. protected void DefineReverse<TDto, TDao>(Action<LoomBuilder<TDto, TDao>> customFromDao)
  48. where TDao : class, IDao<long>, new()
  49. where TDto : class, IDto, new()
  50. {
  51. // from DTO to DAO
  52. var builder = Define<TDto, TDao>();
  53. builder.PublicProperties();
  54. customFromDao?.Invoke(builder);
  55. builder.Compile();
  56. }
  57. protected void DefineReverse<TDto, TDao>()
  58. where TDao : class, IDao<long>, new()
  59. where TDto : class, IDto, new()
  60. {
  61. // from DTO to DAO
  62. var builder = Define<TDto, TDao>();
  63. builder.PublicProperties();
  64. builder.Compile();
  65. }
  66. #endregion
  67. }
  68. }