UnitOfWorkBase.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Immutable;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using Abp.Extensions;
  7. using Abp.Runtime.Session;
  8. using Abp.Utils.Etc;
  9. using Castle.Core;
  10. namespace Abp.Domain.Uow
  11. {
  12. /// <summary>
  13. /// Base for all Unit Of Work classes.
  14. /// </summary>
  15. public abstract class UnitOfWorkBase : IUnitOfWork
  16. {
  17. public string Id { get; }
  18. [DoNotWire]
  19. public IUnitOfWork Outer { get; set; }
  20. /// <inheritdoc/>
  21. public event EventHandler Completed;
  22. /// <inheritdoc/>
  23. public event EventHandler<UnitOfWorkFailedEventArgs> Failed;
  24. /// <inheritdoc/>
  25. public event EventHandler Disposed;
  26. /// <inheritdoc/>
  27. public UnitOfWorkOptions Options { get; private set; }
  28. /// <inheritdoc/>
  29. public IReadOnlyList<DataFilterConfiguration> Filters
  30. {
  31. get { return _filters.ToImmutableList(); }
  32. }
  33. private readonly List<DataFilterConfiguration> _filters;
  34. public Dictionary<string, object> Items { get; set; }
  35. /// <summary>
  36. /// Gets default UOW options.
  37. /// </summary>
  38. protected IUnitOfWorkDefaultOptions DefaultOptions { get; }
  39. /// <summary>
  40. /// Gets the connection string resolver.
  41. /// </summary>
  42. protected IConnectionStringResolver ConnectionStringResolver { get; }
  43. /// <summary>
  44. /// Gets a value indicates that this unit of work is disposed or not.
  45. /// </summary>
  46. public bool IsDisposed { get; private set; }
  47. /// <summary>
  48. /// Reference to current ABP session.
  49. /// </summary>
  50. public IAbpSession AbpSession { protected get; set; }
  51. protected IUnitOfWorkFilterExecuter FilterExecuter { get; }
  52. /// <summary>
  53. /// Is <see cref="Begin"/> method called before?
  54. /// </summary>
  55. private bool _isBeginCalledBefore;
  56. /// <summary>
  57. /// Is <see cref="Complete"/> method called before?
  58. /// </summary>
  59. private bool _isCompleteCalledBefore;
  60. /// <summary>
  61. /// Is this unit of work successfully completed.
  62. /// </summary>
  63. private bool _succeed;
  64. /// <summary>
  65. /// A reference to the exception if this unit of work failed.
  66. /// </summary>
  67. private Exception _exception;
  68. private int? _tenantId;
  69. /// <summary>
  70. /// Constructor.
  71. /// </summary>
  72. protected UnitOfWorkBase(
  73. IConnectionStringResolver connectionStringResolver,
  74. IUnitOfWorkDefaultOptions defaultOptions,
  75. IUnitOfWorkFilterExecuter filterExecuter)
  76. {
  77. FilterExecuter = filterExecuter;
  78. DefaultOptions = defaultOptions;
  79. ConnectionStringResolver = connectionStringResolver;
  80. Id = Guid.NewGuid().ToString("N");
  81. _filters = defaultOptions.Filters.ToList();
  82. AbpSession = NullAbpSession.Instance;
  83. Items = new Dictionary<string, object>();
  84. }
  85. /// <inheritdoc/>
  86. public void Begin(UnitOfWorkOptions options)
  87. {
  88. Check.NotNull(options, nameof(options));
  89. PreventMultipleBegin();
  90. Options = options; //TODO: Do not set options like that, instead make a copy?
  91. SetFilters(options.FilterOverrides);
  92. SetTenantId(AbpSession.TenantId, false);
  93. BeginUow();
  94. }
  95. /// <inheritdoc/>
  96. public abstract void SaveChanges();
  97. /// <inheritdoc/>
  98. public abstract Task SaveChangesAsync();
  99. /// <inheritdoc/>
  100. public IDisposable DisableFilter(params string[] filterNames)
  101. {
  102. //TODO: Check if filters exists?
  103. var disabledFilters = new List<string>();
  104. foreach (var filterName in filterNames)
  105. {
  106. var filterIndex = GetFilterIndex(filterName);
  107. if (_filters[filterIndex].IsEnabled)
  108. {
  109. disabledFilters.Add(filterName);
  110. _filters[filterIndex] = new DataFilterConfiguration(_filters[filterIndex], false);
  111. }
  112. }
  113. disabledFilters.ForEach(ApplyDisableFilter);
  114. return new DisposeAction(() => EnableFilter(disabledFilters.ToArray()));
  115. }
  116. /// <inheritdoc/>
  117. public IDisposable EnableFilter(params string[] filterNames)
  118. {
  119. //TODO: Check if filters exists?
  120. var enabledFilters = new List<string>();
  121. foreach (var filterName in filterNames)
  122. {
  123. var filterIndex = GetFilterIndex(filterName);
  124. if (!_filters[filterIndex].IsEnabled)
  125. {
  126. enabledFilters.Add(filterName);
  127. _filters[filterIndex] = new DataFilterConfiguration(_filters[filterIndex], true);
  128. }
  129. }
  130. enabledFilters.ForEach(ApplyEnableFilter);
  131. return new DisposeAction(() => DisableFilter(enabledFilters.ToArray()));
  132. }
  133. /// <inheritdoc/>
  134. public bool IsFilterEnabled(string filterName)
  135. {
  136. return GetFilter(filterName).IsEnabled;
  137. }
  138. /// <inheritdoc/>
  139. public IDisposable SetFilterParameter(string filterName, string parameterName, object value)
  140. {
  141. var filterIndex = GetFilterIndex(filterName);
  142. var newfilter = new DataFilterConfiguration(_filters[filterIndex]);
  143. //Store old value
  144. object oldValue = null;
  145. var hasOldValue = newfilter.FilterParameters.ContainsKey(parameterName);
  146. if (hasOldValue)
  147. {
  148. oldValue = newfilter.FilterParameters[parameterName];
  149. }
  150. newfilter.FilterParameters[parameterName] = value;
  151. _filters[filterIndex] = newfilter;
  152. ApplyFilterParameterValue(filterName, parameterName, value);
  153. return new DisposeAction(() =>
  154. {
  155. //Restore old value
  156. if (hasOldValue)
  157. {
  158. SetFilterParameter(filterName, parameterName, oldValue);
  159. }
  160. });
  161. }
  162. public virtual IDisposable SetTenantId(int? tenantId)
  163. {
  164. return SetTenantId(tenantId, true);
  165. }
  166. public virtual IDisposable SetTenantId(int? tenantId, bool switchMustHaveTenantEnableDisable)
  167. {
  168. var oldTenantId = _tenantId;
  169. _tenantId = tenantId;
  170. IDisposable mustHaveTenantEnableChange;
  171. if (switchMustHaveTenantEnableDisable)
  172. {
  173. mustHaveTenantEnableChange = tenantId == null
  174. ? DisableFilter(AbpDataFilters.MustHaveTenant)
  175. : EnableFilter(AbpDataFilters.MustHaveTenant);
  176. }
  177. else
  178. {
  179. mustHaveTenantEnableChange = NullDisposable.Instance;
  180. }
  181. var mayHaveTenantChange = SetFilterParameter(AbpDataFilters.MayHaveTenant, AbpDataFilters.Parameters.TenantId, tenantId);
  182. var mustHaveTenantChange = SetFilterParameter(AbpDataFilters.MustHaveTenant, AbpDataFilters.Parameters.TenantId, tenantId ?? 0);
  183. return new DisposeAction(() =>
  184. {
  185. mayHaveTenantChange.Dispose();
  186. mustHaveTenantChange.Dispose();
  187. mustHaveTenantEnableChange.Dispose();
  188. _tenantId = oldTenantId;
  189. });
  190. }
  191. public int? GetTenantId()
  192. {
  193. return _tenantId;
  194. }
  195. /// <inheritdoc/>
  196. public void Complete()
  197. {
  198. PreventMultipleComplete();
  199. try
  200. {
  201. CompleteUow();
  202. _succeed = true;
  203. OnCompleted();
  204. }
  205. catch (Exception ex)
  206. {
  207. _exception = ex;
  208. throw;
  209. }
  210. }
  211. /// <inheritdoc/>
  212. public async Task CompleteAsync()
  213. {
  214. PreventMultipleComplete();
  215. try
  216. {
  217. await CompleteUowAsync();
  218. _succeed = true;
  219. OnCompleted();
  220. }
  221. catch (Exception ex)
  222. {
  223. _exception = ex;
  224. throw;
  225. }
  226. }
  227. /// <inheritdoc/>
  228. public void Dispose()
  229. {
  230. if (!_isBeginCalledBefore || IsDisposed)
  231. {
  232. return;
  233. }
  234. IsDisposed = true;
  235. if (!_succeed)
  236. {
  237. OnFailed(_exception);
  238. }
  239. DisposeUow();
  240. OnDisposed();
  241. }
  242. /// <summary>
  243. /// Can be implemented by derived classes to start UOW.
  244. /// </summary>
  245. protected virtual void BeginUow()
  246. {
  247. }
  248. /// <summary>
  249. /// Should be implemented by derived classes to complete UOW.
  250. /// </summary>
  251. protected abstract void CompleteUow();
  252. /// <summary>
  253. /// Should be implemented by derived classes to complete UOW.
  254. /// </summary>
  255. protected abstract Task CompleteUowAsync();
  256. /// <summary>
  257. /// Should be implemented by derived classes to dispose UOW.
  258. /// </summary>
  259. protected abstract void DisposeUow();
  260. protected virtual void ApplyDisableFilter(string filterName)
  261. {
  262. FilterExecuter.ApplyDisableFilter(this, filterName);
  263. }
  264. protected virtual void ApplyEnableFilter(string filterName)
  265. {
  266. FilterExecuter.ApplyEnableFilter(this, filterName);
  267. }
  268. protected virtual void ApplyFilterParameterValue(string filterName, string parameterName, object value)
  269. {
  270. FilterExecuter.ApplyFilterParameterValue(this, filterName, parameterName, value);
  271. }
  272. protected virtual string ResolveConnectionString(ConnectionStringResolveArgs args)
  273. {
  274. return ConnectionStringResolver.GetNameOrConnectionString(args);
  275. }
  276. /// <summary>
  277. /// Called to trigger <see cref="Completed"/> event.
  278. /// </summary>
  279. protected virtual void OnCompleted()
  280. {
  281. Completed.InvokeSafely(this);
  282. }
  283. /// <summary>
  284. /// Called to trigger <see cref="Failed"/> event.
  285. /// </summary>
  286. /// <param name="exception">Exception that cause failure</param>
  287. protected virtual void OnFailed(Exception exception)
  288. {
  289. Failed.InvokeSafely(this, new UnitOfWorkFailedEventArgs(exception));
  290. }
  291. /// <summary>
  292. /// Called to trigger <see cref="Disposed"/> event.
  293. /// </summary>
  294. protected virtual void OnDisposed()
  295. {
  296. Disposed.InvokeSafely(this);
  297. }
  298. private void PreventMultipleBegin()
  299. {
  300. if (_isBeginCalledBefore)
  301. {
  302. throw new AbpException("This unit of work has started before. Can not call Start method more than once.");
  303. }
  304. _isBeginCalledBefore = true;
  305. }
  306. private void PreventMultipleComplete()
  307. {
  308. if (_isCompleteCalledBefore)
  309. {
  310. throw new AbpException("Complete is called before!");
  311. }
  312. _isCompleteCalledBefore = true;
  313. }
  314. private void SetFilters(List<DataFilterConfiguration> filterOverrides)
  315. {
  316. for (var i = 0; i < _filters.Count; i++)
  317. {
  318. var filterOverride = filterOverrides.FirstOrDefault(f => f.FilterName == _filters[i].FilterName);
  319. if (filterOverride != null)
  320. {
  321. _filters[i] = filterOverride;
  322. }
  323. }
  324. if (AbpSession.TenantId == null)
  325. {
  326. ChangeFilterIsEnabledIfNotOverrided(filterOverrides, AbpDataFilters.MustHaveTenant, false);
  327. }
  328. }
  329. private void ChangeFilterIsEnabledIfNotOverrided(List<DataFilterConfiguration> filterOverrides, string filterName, bool isEnabled)
  330. {
  331. if (filterOverrides.Any(f => f.FilterName == filterName))
  332. {
  333. return;
  334. }
  335. var index = _filters.FindIndex(f => f.FilterName == filterName);
  336. if (index < 0)
  337. {
  338. return;
  339. }
  340. if (_filters[index].IsEnabled == isEnabled)
  341. {
  342. return;
  343. }
  344. _filters[index] = new DataFilterConfiguration(filterName, isEnabled);
  345. }
  346. private DataFilterConfiguration GetFilter(string filterName)
  347. {
  348. var filter = _filters.FirstOrDefault(f => f.FilterName == filterName);
  349. if (filter == null)
  350. {
  351. throw new AbpException("Unknown filter name: " + filterName + ". Be sure this filter is registered before.");
  352. }
  353. return filter;
  354. }
  355. private int GetFilterIndex(string filterName)
  356. {
  357. var filterIndex = _filters.FindIndex(f => f.FilterName == filterName);
  358. if (filterIndex < 0)
  359. {
  360. throw new AbpException("Unknown filter name: " + filterName + ". Be sure this filter is registered before.");
  361. }
  362. return filterIndex;
  363. }
  364. public override string ToString()
  365. {
  366. return $"[UnitOfWork {Id}]";
  367. }
  368. }
  369. }