UnitOfWork.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using System.Diagnostics;
  3. using Quadarax.Foundation.Core.Data.Interface.Domain;
  4. using Quadarax.Foundation.Core.Object;
  5. namespace Quadarax.Foundation.Core.Data.Domain
  6. {
  7. public class UnitOfWork<TDomainContext> : DisposableObject, IUnitOfWork<TDomainContext> where TDomainContext : IDomain
  8. {
  9. public TDomainContext Context { get; protected set; }
  10. public Guid Stamp { get; protected set; }
  11. public int CtxHash => Context.GetHashCode();
  12. public UnitOfWork(IDomainContextResolver context,Guid? customStamp = null)
  13. {
  14. Context = context.GetCurrent<TDomainContext>();
  15. if (customStamp == null)
  16. customStamp = Guid.NewGuid();
  17. Stamp = customStamp.GetValueOrDefault();
  18. Debug.WriteLine($"UOW>>> {Stamp:D} [CTX:{CtxHash}] created");
  19. }
  20. public UnitOfWork(TDomainContext context, Guid? customStamp = null)
  21. {
  22. Context = context;
  23. if (customStamp == null)
  24. customStamp = Guid.NewGuid();
  25. Stamp = customStamp.GetValueOrDefault();
  26. Debug.WriteLine($"UOW>>> {Stamp:D} [CTX:{CtxHash}] created");
  27. }
  28. public void Commit()
  29. {
  30. Context.Commit();
  31. Debug.WriteLine($"UOW>>> {Stamp:D} [CTX:{CtxHash}] commited");
  32. }
  33. public IUnitOfWork<TCustomDomainContext> As<TCustomDomainContext>() where TCustomDomainContext : IDomain
  34. {
  35. return new UnitOfWork<TCustomDomainContext>((TCustomDomainContext)(IDomain)Context, Stamp);
  36. }
  37. protected override void OnDisposing()
  38. {
  39. Debug.WriteLine($"UOW>>> {Stamp:D} [CTX:{CtxHash}] disposed");
  40. Context?.Rollback();
  41. Context = default;
  42. }
  43. }
  44. }