UnitOfWorkRegistrar.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System.Linq;
  2. using System.Reflection;
  3. using Abp.Dependency;
  4. using Castle.Core;
  5. using Castle.MicroKernel;
  6. namespace Abp.Domain.Uow
  7. {
  8. /// <summary>
  9. /// This class is used to register interceptor for needed classes for Unit Of Work mechanism.
  10. /// </summary>
  11. internal static class UnitOfWorkRegistrar
  12. {
  13. /// <summary>
  14. /// Initializes the registerer.
  15. /// </summary>
  16. /// <param name="iocManager">IOC manager</param>
  17. public static void Initialize(IIocManager iocManager)
  18. {
  19. iocManager.IocContainer.Kernel.ComponentRegistered += (key, handler) =>
  20. {
  21. var implementationType = handler.ComponentModel.Implementation.GetTypeInfo();
  22. HandleTypesWithUnitOfWorkAttribute(implementationType, handler);
  23. HandleConventionalUnitOfWorkTypes(iocManager, implementationType, handler);
  24. };
  25. }
  26. private static void HandleTypesWithUnitOfWorkAttribute(TypeInfo implementationType, IHandler handler)
  27. {
  28. if (IsUnitOfWorkType(implementationType) || AnyMethodHasUnitOfWork(implementationType))
  29. {
  30. handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(UnitOfWorkInterceptor)));
  31. }
  32. }
  33. private static void HandleConventionalUnitOfWorkTypes(IIocManager iocManager, TypeInfo implementationType, IHandler handler)
  34. {
  35. if (!iocManager.IsRegistered<IUnitOfWorkDefaultOptions>())
  36. {
  37. return;
  38. }
  39. var uowOptions = iocManager.Resolve<IUnitOfWorkDefaultOptions>();
  40. if (uowOptions.IsConventionalUowClass(implementationType.AsType()))
  41. {
  42. handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(UnitOfWorkInterceptor)));
  43. }
  44. }
  45. private static bool IsUnitOfWorkType(TypeInfo implementationType)
  46. {
  47. return UnitOfWorkHelper.HasUnitOfWorkAttribute(implementationType);
  48. }
  49. private static bool AnyMethodHasUnitOfWork(TypeInfo implementationType)
  50. {
  51. return implementationType
  52. .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
  53. .Any(UnitOfWorkHelper.HasUnitOfWorkAttribute);
  54. }
  55. }
  56. }