Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public abstract class BaseNotificationHandler<TDomainEvent> : BaseEventHandler, INotificationHandler<TDomainEvent> where TDomainEvent : DomainEvent
- {
- public BaseNotificationHandler(ILoggerAdapter logger) : base(logger) { }
- /// <summary>
- /// Handles domain event.
- /// </summary>
- /// <param name="domainEvent">Domain event.</param>
- /// <param name="cancellationToken">Cancellation token.</param>
- public async Task Handle(TDomainEvent domainEvent, CancellationToken cancellationToken)
- {
- try
- {
- if (...) // Some notification validation logic.
- {
- await HandleNotification(domainEvent, cancellationToken);
- logger.LogDebug($"Complete handle notification: {GetUniqueEventAndHandlerKey(domainEvent)}");
- }
- }
- catch (Exception ex)
- {
- logger.LogError($"Exception handling event, exception: {ex.ToString()}");
- // Rethrow exception to caller to handle.
- throw;
- }
- }
- /// <summary>
- /// Actual implementation of notification handling.
- /// </summary>
- /// <param name="notification">Notification.</param>
- /// <param name="cancellationToken">Cancellation token.</param>
- protected abstract Task HandleNotification(TDomainEvent notification, CancellationToken cancellationToken);
- }
- public class DemoEventHandler : BaseNotificationHandler<SetDemoDataEvent>
- {
- public DemoEventHandler(ILoggerAdapter<DemoEventHandler> logger) : base(logger) { }
- protected override Task HandleNotification(SetDemoDataEvent notification, CancellationToken cancellationToken)
- {
- File.AppendAllText(@"E:\test.txt", $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")} - some notification: {JsonConvert.SerializeObject(notification)}{Environment.NewLine}");
- return Task.CompletedTask;
- }
- }
- public static class DependencyInjectionHelper
- {
- /// <summary>
- /// Check is type implementing INotificationHandler.
- /// </summary>
- /// <param name="type">Type.</param>
- /// <returns>True if type or its base class is implementing IDomainEventHandler, otherwise false.</returns>
- private static bool IsAssignableFromINotificationHandler(Type type)
- {
- return IsImplementInterface(typeof(INotificationHandler<>), type);
- }
- /// <summary>
- /// Check is type implementing IRequestHandler.
- /// </summary>
- /// <param name="type">Type.</param>
- /// <returns>True if type or its base class is implementing IDomainEventHandlerWithResult, otherwise false.</returns>
- private static bool IsAssignableFromIRequestHandler(Type type)
- {
- return IsImplementInterface(typeof(IRequestHandler<,>), type);
- }
- /// <summary>
- /// Check is type implementing IRepositoryFactory.
- /// </summary>
- /// <param name="type">Type.</param>
- /// <returns>True if type or its base class is implementing IDomainEventHandlerWithResult, otherwise false.</returns>
- private static bool IsAssignableFromIRepositoryFactory(Type type)
- {
- return IsImplementInterface(typeof(IRepositoryFactory<>), type);
- }
- /// <summary>
- /// Logic to check is type implementing baseType.
- /// </summary>
- /// <param name="interfaceType">Base type.</param>
- /// <param name="type">Type.</param>
- /// <returns>Returns true if type is implementing baseType.</returns>
- private static bool IsImplementInterface(Type interfaceType, Type type)
- {
- var typeInfo = type.GetTypeInfo();
- var result = typeInfo.IsClass && !typeInfo.IsAbstract;
- if (result)
- {
- result = typeInfo.ImplementedInterfaces.Any(t => t.GetTypeInfo().IsGenericType && t.GetGenericTypeDefinition() == interfaceType);
- }
- return result;
- }
- /// <summary>
- /// Returns all IRequestHandler and INotificationHandler assemblies.
- /// </summary>
- /// <param name="services">Service collection.</param>
- private static IEnumerable<TypeInfo> GetAllRequestAndNotificationHandlerAssemblies()
- {
- // Get all classes in all assemblies.
- var allAssemblies = GetAllTypes();
- var domainNotificationHandlerTypes = allAssemblies.Where(IsAssignableFromINotificationHandler);
- var domainRequestHandlerTypes = allAssemblies.Where(IsAssignableFromIRequestHandler).ToList();
- domainRequestHandlerTypes.AddRange(domainNotificationHandlerTypes);
- return domainRequestHandlerTypes;
- }
- public static IServiceCollection AddMediatRServices(this IServiceCollection services)
- {
- services.AddScoped(typeof(ILoggerAdapter<>), typeof(LoggerAdapter<>));
- AddRepositoryFactoryAssemblies(services);
- var mediatRServices = GetAllRequestAndNotificationHandlerAssemblies();
- services.AddMediatR(mediatRServices);
- return services;
- }
Add Comment
Please, Sign In to add comment