Mapper.cs 2.5 KB

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