UnitOfWorkManager.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System.Linq;
  2. using System.Transactions;
  3. using Abp.Dependency;
  4. namespace Abp.Domain.Uow
  5. {
  6. /// <summary>
  7. /// Unit of work manager.
  8. /// </summary>
  9. internal class UnitOfWorkManager : IUnitOfWorkManager, ITransientDependency
  10. {
  11. private readonly IIocResolver _iocResolver;
  12. private readonly ICurrentUnitOfWorkProvider _currentUnitOfWorkProvider;
  13. private readonly IUnitOfWorkDefaultOptions _defaultOptions;
  14. public IActiveUnitOfWork Current
  15. {
  16. get { return _currentUnitOfWorkProvider.Current; }
  17. }
  18. public UnitOfWorkManager(
  19. IIocResolver iocResolver,
  20. ICurrentUnitOfWorkProvider currentUnitOfWorkProvider,
  21. IUnitOfWorkDefaultOptions defaultOptions)
  22. {
  23. _iocResolver = iocResolver;
  24. _currentUnitOfWorkProvider = currentUnitOfWorkProvider;
  25. _defaultOptions = defaultOptions;
  26. }
  27. public IUnitOfWorkCompleteHandle Begin()
  28. {
  29. return Begin(new UnitOfWorkOptions());
  30. }
  31. public IUnitOfWorkCompleteHandle Begin(TransactionScopeOption scope)
  32. {
  33. return Begin(new UnitOfWorkOptions { Scope = scope });
  34. }
  35. public IUnitOfWorkCompleteHandle Begin(UnitOfWorkOptions options)
  36. {
  37. options.FillDefaultsForNonProvidedOptions(_defaultOptions);
  38. var outerUow = _currentUnitOfWorkProvider.Current;
  39. if (options.Scope == TransactionScopeOption.Required && outerUow != null)
  40. {
  41. return new InnerUnitOfWorkCompleteHandle();
  42. }
  43. var uow = _iocResolver.Resolve<IUnitOfWork>();
  44. uow.Completed += (sender, args) =>
  45. {
  46. _currentUnitOfWorkProvider.Current = null;
  47. };
  48. uow.Failed += (sender, args) =>
  49. {
  50. _currentUnitOfWorkProvider.Current = null;
  51. };
  52. uow.Disposed += (sender, args) =>
  53. {
  54. _iocResolver.Release(uow);
  55. };
  56. //Inherit filters from outer UOW
  57. if (outerUow != null)
  58. {
  59. options.FillOuterUowFiltersForNonProvidedOptions(outerUow.Filters.ToList());
  60. }
  61. uow.Begin(options);
  62. //Inherit tenant from outer UOW
  63. if (outerUow != null)
  64. {
  65. uow.SetTenantId(outerUow.GetTenantId(), false);
  66. }
  67. _currentUnitOfWorkProvider.Current = uow;
  68. return uow;
  69. }
  70. }
  71. }