Guest User

Untitled

a guest
May 24th, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.77 KB | None | 0 0
  1. public abstract class BaseNotificationHandler<TDomainEvent> : BaseEventHandler, INotificationHandler<TDomainEvent> where TDomainEvent : DomainEvent
  2. {
  3. public BaseNotificationHandler(ILoggerAdapter logger) : base(logger) { }
  4.  
  5. /// <summary>
  6. /// Handles domain event.
  7. /// </summary>
  8. /// <param name="domainEvent">Domain event.</param>
  9. /// <param name="cancellationToken">Cancellation token.</param>
  10. public async Task Handle(TDomainEvent domainEvent, CancellationToken cancellationToken)
  11. {
  12. try
  13. {
  14. if (...) // Some notification validation logic.
  15. {
  16. await HandleNotification(domainEvent, cancellationToken);
  17. logger.LogDebug($"Complete handle notification: {GetUniqueEventAndHandlerKey(domainEvent)}");
  18. }
  19. }
  20. catch (Exception ex)
  21. {
  22. logger.LogError($"Exception handling event, exception: {ex.ToString()}");
  23.  
  24. // Rethrow exception to caller to handle.
  25. throw;
  26. }
  27. }
  28.  
  29. /// <summary>
  30. /// Actual implementation of notification handling.
  31. /// </summary>
  32. /// <param name="notification">Notification.</param>
  33. /// <param name="cancellationToken">Cancellation token.</param>
  34. protected abstract Task HandleNotification(TDomainEvent notification, CancellationToken cancellationToken);
  35. }
  36.  
  37. public class DemoEventHandler : BaseNotificationHandler<SetDemoDataEvent>
  38. {
  39. public DemoEventHandler(ILoggerAdapter<DemoEventHandler> logger) : base(logger) { }
  40.  
  41. protected override Task HandleNotification(SetDemoDataEvent notification, CancellationToken cancellationToken)
  42. {
  43. File.AppendAllText(@"E:\test.txt", $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")} - some notification: {JsonConvert.SerializeObject(notification)}{Environment.NewLine}");
  44.  
  45. return Task.CompletedTask;
  46. }
  47. }
  48.  
  49. public static class DependencyInjectionHelper
  50. {
  51. /// <summary>
  52. /// Check is type implementing INotificationHandler.
  53. /// </summary>
  54. /// <param name="type">Type.</param>
  55. /// <returns>True if type or its base class is implementing IDomainEventHandler, otherwise false.</returns>
  56. private static bool IsAssignableFromINotificationHandler(Type type)
  57. {
  58. return IsImplementInterface(typeof(INotificationHandler<>), type);
  59. }
  60.  
  61. /// <summary>
  62. /// Check is type implementing IRequestHandler.
  63. /// </summary>
  64. /// <param name="type">Type.</param>
  65. /// <returns>True if type or its base class is implementing IDomainEventHandlerWithResult, otherwise false.</returns>
  66. private static bool IsAssignableFromIRequestHandler(Type type)
  67. {
  68. return IsImplementInterface(typeof(IRequestHandler<,>), type);
  69. }
  70.  
  71. /// <summary>
  72. /// Check is type implementing IRepositoryFactory.
  73. /// </summary>
  74. /// <param name="type">Type.</param>
  75. /// <returns>True if type or its base class is implementing IDomainEventHandlerWithResult, otherwise false.</returns>
  76. private static bool IsAssignableFromIRepositoryFactory(Type type)
  77. {
  78. return IsImplementInterface(typeof(IRepositoryFactory<>), type);
  79. }
  80.  
  81. /// <summary>
  82. /// Logic to check is type implementing baseType.
  83. /// </summary>
  84. /// <param name="interfaceType">Base type.</param>
  85. /// <param name="type">Type.</param>
  86. /// <returns>Returns true if type is implementing baseType.</returns>
  87. private static bool IsImplementInterface(Type interfaceType, Type type)
  88. {
  89. var typeInfo = type.GetTypeInfo();
  90. var result = typeInfo.IsClass && !typeInfo.IsAbstract;
  91.  
  92. if (result)
  93. {
  94. result = typeInfo.ImplementedInterfaces.Any(t => t.GetTypeInfo().IsGenericType && t.GetGenericTypeDefinition() == interfaceType);
  95. }
  96.  
  97. return result;
  98. }
  99.  
  100. /// <summary>
  101. /// Returns all IRequestHandler and INotificationHandler assemblies.
  102. /// </summary>
  103. /// <param name="services">Service collection.</param>
  104. private static IEnumerable<TypeInfo> GetAllRequestAndNotificationHandlerAssemblies()
  105. {
  106. // Get all classes in all assemblies.
  107. var allAssemblies = GetAllTypes();
  108. var domainNotificationHandlerTypes = allAssemblies.Where(IsAssignableFromINotificationHandler);
  109. var domainRequestHandlerTypes = allAssemblies.Where(IsAssignableFromIRequestHandler).ToList();
  110. domainRequestHandlerTypes.AddRange(domainNotificationHandlerTypes);
  111.  
  112. return domainRequestHandlerTypes;
  113. }
  114.  
  115. public static IServiceCollection AddMediatRServices(this IServiceCollection services)
  116. {
  117. services.AddScoped(typeof(ILoggerAdapter<>), typeof(LoggerAdapter<>));
  118.  
  119. AddRepositoryFactoryAssemblies(services);
  120.  
  121. var mediatRServices = GetAllRequestAndNotificationHandlerAssemblies();
  122. services.AddMediatR(mediatRServices);
  123.  
  124. return services;
  125. }
Add Comment
Please, Sign In to add comment