DomainContextResolver.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Quadarax.Foundation.Core.Data.Interface.Domain;
  5. using Quadarax.Foundation.Core.Object;
  6. namespace Quadarax.Foundation.Core.Data.Domain
  7. {
  8. public class DomainContextResolver : DisposableObject, IDomainContextResolver
  9. {
  10. private readonly IDictionary<string, IDomain> _contextCache;
  11. public string[] RegisteredContexts => _contextCache.Keys.ToArray();
  12. public DomainContextResolver()
  13. {
  14. _contextCache = new Dictionary<string, IDomain>();
  15. }
  16. public IDomain Get(string typeFullName)
  17. {
  18. if (!_contextCache.ContainsKey(typeFullName))
  19. throw new InvalidOperationException($"Domain context '{typeFullName}' not found in DomainContextResolver. Not registered.");
  20. return _contextCache[typeFullName];
  21. }
  22. public TDomainContext Register<TDomainContext>(TDomainContext context) where TDomainContext : IDomain
  23. {
  24. if (_contextCache.ContainsKey(typeof(TDomainContext).FullName!))
  25. throw new InvalidOperationException($"Domain context '{typeof(TDomainContext).FullName}' is already registered.");
  26. _contextCache.Add(typeof(TDomainContext).FullName!, context);
  27. return GetCurrent<TDomainContext>();
  28. }
  29. public TDomainContext GetCurrent<TDomainContext>() where TDomainContext : IDomain
  30. {
  31. if (!_contextCache.ContainsKey(typeof(TDomainContext).FullName!))
  32. throw new InvalidOperationException($"Domain context '{typeof(TDomainContext).FullName}' not found in DomainContextResolver. Not registered.");
  33. return (TDomainContext)_contextCache[typeof(TDomainContext).FullName!];
  34. }
  35. protected override void OnDisposing()
  36. {
  37. if (_contextCache != null)
  38. {
  39. foreach (var context in _contextCache.Values)
  40. {
  41. context.Dispose();
  42. }
  43. }
  44. }
  45. }
  46. }