Пример #1
0
        public object[] ResolveAll(Type type, object argumentsAsAnonymousType)
        {
            var resolvedObjects = argumentsAsAnonymousType != null
                ? _iocResolver.ResolveAll(type, argumentsAsAnonymousType)
                : _iocResolver.ResolveAll(type);

            _resolvedObjects.AddRange(resolvedObjects);
            return(resolvedObjects);
        }
Пример #2
0
        public void Publish <TEvent>(TEvent @event) where TEvent : IEvent
        {
            if (@event == null)
            {
                throw new ArgumentNullException(nameof(@event));
            }

            var eventHandlers = _resolver.ResolveAll <IEventHandler <TEvent> >();

            foreach (var handler in eventHandlers)
            {
                handler.Handle(@event);
            }
        }
Пример #3
0
        public async Task DispatchAsync(
            IEnumerable <IDomainEvent> domainEvents,
            CancellationToken cancellationToken)
        {
            foreach (var domainEvent in domainEvents)
            {
                var subscriberInfomation = await GetSubscriberInfomationAsync(domainEvent.GetType(), cancellationToken).ConfigureAwait(false);

                var subscribers             = _resolver.ResolveAll(subscriberInfomation.SubscriberType);
                var subscriberDispatchTasks = subscribers
                                              .Select(s => DispatchToSubscriberAsync(s, subscriberInfomation, domainEvent, cancellationToken))
                                              .ToList();

                try
                {
                    await Task.WhenAll(subscriberDispatchTasks).ConfigureAwait(false);
                }
                catch (Exception exception)
                {
                    if (_eventFlowConfiguration.ThrowSubscriberExceptions)
                    {
                        throw;
                    }

                    _log.Error(
                        exception,
                        $"Event subscribers of event '{domainEvent.EventType.PrettyPrint()}' threw an unexpected exception!");
                }
            }
        }
Пример #4
0
        private IDictionary <IDependency, IInstantiationPoint> GetServiceMap()
        {
            var points = _registry.GetAllRegisteredPoints();
            var map    = _resolver.ResolveAll(points);

            return(map);
        }
Пример #5
0
        private async Task DispatchToSubscribersAsync(IntegrationEvent integrationEvent)
        {
            var subscribers = _resolver
                              .ResolveAll(typeof(IStreamsDbSubscriber))
                              .Cast <IStreamsDbSubscriber>()
                              .ToList();

            if (!subscribers.Any())
            {
                _log.Debug(() => $"Didn't find any subscribers to '{integrationEvent.Metadata.EventName}'");
            }

            foreach (var subscriber in subscribers)
            {
                _log.Verbose(() => $"Calling HandleAsync on handler '{subscriber.GetType().PrettyPrint()}' " +
                             $"for aggregate event '{integrationEvent.Metadata.EventName}'");

                try
                {
                    var executionResult = await subscriber.HandleAsync(integrationEvent);

                    if (!executionResult.IsSuccess)
                    {
                        throw new Exception("Execution is not succesfull");
                    }
                }
                catch (Exception e)
                {
                    _log.Error(e, $"Subscriber '{subscriber.GetType().PrettyPrint()}' threw " +
                               $"'{e.GetType().PrettyPrint()}' while handling '{integrationEvent.Metadata.EventName}': {e.Message}");
                    throw;
                }
            }
        }
Пример #6
0
        private async Task DispatchToSubscribersAsync(
            IDomainEvent domainEvent,
            IResolver resolver,
            Type subscriberType,
            bool swallowException,
            CancellationToken cancellationToken)
        {
            var subscriberInfomation = await GetSubscriberInfomationAsync(
                domainEvent.GetType(),
                subscriberType,
                cancellationToken)
                                       .ConfigureAwait(false);

            var subscribers = resolver.ResolveAll(subscriberInfomation.SubscriberType);

            foreach (var subscriber in subscribers)
            {
                _log.Verbose(() => $"Calling HandleAsync on handler '{subscriber.GetType().PrettyPrint()}' " +
                             $"for aggregate event '{domainEvent.EventType.PrettyPrint()}'");

                try
                {
                    await subscriberInfomation.HandleMethod(subscriber, domainEvent, cancellationToken).ConfigureAwait(false);
                }
                catch (Exception e) when(swallowException)
                {
                    _log.Error(e, $"Subscriber '{subscriberInfomation.SubscriberType.PrettyPrint()}' threw " +
                               $"'{e.GetType().PrettyPrint()}' while handling '{domainEvent.EventType.PrettyPrint()}': {e.Message}");
                }
            }
        }
Пример #7
0
        private IEnumerable <T> ResolveAll <T>() where T : class, IHandler
        {
            IEnumerable <T> handlers;

            try
            {
                _logger.LogDebug(Text.FindingHandler <T>());
                handlers = _resolver.ResolveAll <T>();
                foreach (var handler in handlers)
                {
                    _logger.LogInfo(Text.FoundHandler <T>(handler));
                }
            }
            catch (Exception ex)
            {
                var msg = Text.HandlerCreationError <T>();
                _logger.LogError(msg);
                throw new Exception(msg, ex);
            }
            if (handlers.Count() == 0)
            {
                _logger.LogWarn(Text.FoundNoHandler <T>());
            }

            return(handlers);
        }
Пример #8
0
 public static IEnumerable <object> ResolveAll(this IResolver resolver, Type contractType, string identifier)
 {
     return(resolver.ResolveAll(new InjectionContext
     {
         Container = resolver.Container,
         ContractType = contractType,
         Identifier = identifier
     }));
 }
Пример #9
0
        public async Task Continues_to_execution_if_handler_resolved()
        {
            // Arrange
            var handlers = new List <IHandleEvent <TestEvent> > {
                _handler
            };

            _resolver.ResolveAll <IHandleEvent <TestEvent> >().Returns(handlers);

            // Act
            var dispatcher = CreateDispatcher();
            var evnt       = new TestEvent();
            await dispatcher.PublishAsync(evnt);

            // Assert
            _resolver.Received(1).ResolveAll <IHandleEvent <TestEvent> >();
            await _executor.Received(1).ExecuteAsync(handlers, evnt, CancellationToken.None);
        }
Пример #10
0
        public void Publish <T>(T evt) where T : IEvent
        {
            var handlerType   = typeof(IEventHandler <>).MakeGenericType(evt.GetType());
            var eventHandlers = _resolver.ResolveAll(handlerType);

            foreach (var eventHandler in eventHandlers)
            {
                handlerType.GetMethod("Handle").Invoke(eventHandler, new object[] { evt });
            }
        }
Пример #11
0
        /// <inheritdoc />
        public async Task PublishAsync <TEvent>(TEvent @event) where TEvent : IEvent
        {
            if (@event == null)
            {
                throw new ArgumentNullException(nameof(@event));
            }

            var handlers = _resolver.ResolveAll <IEventHandlerAsync <TEvent> >();

            foreach (var handler in handlers)
            {
                await handler.HandleAsync(@event);
            }

            if (@event is IBusMessage message)
            {
                await _busMessageDispatcher.DispatchAsync(message);
            }
        }
Пример #12
0
        public TextDbContext Create()
        {
            var dataProvider = _resolver.ResolveAll <IDataProvider>().SingleOrDefault(x => x.Provider == DataConfiguration.Provider);

            if (dataProvider == null)
            {
                throw new Exception("The Data Provider entry in appsettings.json is empty or the one specified has not been found!");
            }

            return(dataProvider.CreateDbContext(ConnectionStrings.DefaultConnection));
        }
Пример #13
0
        public async Task PublishAsync <TEvent>(TEvent @event) where TEvent : IEvent
        {
            Guard.AgainstArgumentNull(@event);

            var handlers = _resolver.ResolveAll <IEventHandlerAsync <TEvent> >();

            foreach (var handler in handlers)
            {
                await handler.HandleAsync(@event);
            }
        }
Пример #14
0
        public static IEnumerable <T> ResolveAll <T>(this IResolver resolver)
        {
            if (resolver == null)
            {
                throw new ArgumentNullException(nameof(resolver));
            }

            var type = typeof(T);

            return(resolver.ResolveAll(type).Cast <T>());
        }
Пример #15
0
        public WeapsyDbContext Create()
        {
            var dataProvider = _resolver.ResolveAll <IDataProvider>().SingleOrDefault(x => x.Provider == DataConfiguration.Provider);

            if (dataProvider == null)
            {
                throw new Exception(ErrorMessage);
            }

            return(dataProvider.CreateDbContext(ConnectionStrings.DefaultConnection));
        }
Пример #16
0
        private IEnumerable <THandler> GetHandlers <THandler, TEvent>(TEvent @event) where TEvent : IEvent
        {
            if (@event == null)
            {
                throw new ArgumentNullException(nameof(@event));
            }

            var eventHandlers = _resolver.ResolveAll <THandler>();

            return(eventHandlers);
        }
Пример #17
0
 public async Task DispatchAsync(IEnumerable <IDomainEvent> domainEvents)
 {
     foreach (var domainEvent in domainEvents)
     {
         var subscriberInfomation    = GetSubscriberInfomation(domainEvent.EventType);
         var subscribers             = _resolver.ResolveAll(subscriberInfomation.SubscriberType);
         var subscriberDispatchTasks = subscribers
                                       .Select(s => DispatchToSubscriberAsync(s, subscriberInfomation, domainEvent))
                                       .ToList();
         await Task.WhenAll(subscriberDispatchTasks).ConfigureAwait(false);
     }
 }
        private async Task DispatchToSubscribersAsync(
            IDomainEvent domainEvent,
            Type subscriberType,
            bool swallowException,
            CancellationToken cancellationToken)
        {
            var subscriberInformation = await GetSubscriberInformationAsync(
                domainEvent.GetType(),
                subscriberType,
                cancellationToken)
                                        .ConfigureAwait(false);

            var subscribers = _resolver.ResolveAll(subscriberInformation.SubscriberType)
                              .Cast <ISubscribe>()
                              .OrderBy(s => s.GetType().Name)
                              .ToList();

            if (!subscribers.Any())
            {
                _log.Debug(() => $"Didn't find any subscribers to '{domainEvent.EventType.PrettyPrint()}'");
                return;
            }

            var exceptions = new List <Exception>();

            foreach (var subscriber in subscribers)
            {
                try
                {
                    await DispatchToSubscriberAsync(
                        domainEvent,
                        subscriber,
                        subscriberInformation,
                        swallowException,
                        cancellationToken)
                    .ConfigureAwait(false);
                }
                catch (Exception e)
                {
                    exceptions.Add(e);
                }
            }

            if (exceptions.Any())
            {
                throw new AggregateException(
                          $"Dispatch of domain event {domainEvent.GetType().PrettyPrint()} to subscribers failed",
                          exceptions);
            }
        }
Пример #19
0
        private Task <IReadOnlyCollection <IDomainEvent> > ExecuteCommandAsync <TAggregate, TIdentity, TSourceIdentity>(
            ICommand <TAggregate, TIdentity, TSourceIdentity> command,
            CancellationToken cancellationToken)
            where TAggregate : IAggregateRoot <TIdentity>
            where TIdentity : IIdentity
            where TSourceIdentity : ISourceId
        {
            var commandType             = command.GetType();
            var commandExecutionDetails = GetCommandExecutionDetails(commandType);

            var commandHandlers = _resolver.ResolveAll(commandExecutionDetails.CommandHandlerType)
                                  .Cast <ICommandHandler>()
                                  .ToList();

            if (!commandHandlers.Any())
            {
                throw new NoCommandHandlersException(string.Format(
                                                         "No command handlers registered for the command '{0}' on aggregate '{1}'",
                                                         commandType.PrettyPrint(),
                                                         typeof(TAggregate).PrettyPrint()));
            }
            if (commandHandlers.Count > 1)
            {
                throw new InvalidOperationException(string.Format(
                                                        "Too many command handlers the command '{0}' on aggregate '{1}'. These were found: {2}",
                                                        commandType.PrettyPrint(),
                                                        typeof(TAggregate).PrettyPrint(),
                                                        string.Join(", ", commandHandlers.Select(h => h.GetType().PrettyPrint()))));
            }

            var commandHandler = commandHandlers.Single();

            return(_transientFaultHandler.TryAsync(
                       async c =>
            {
                var aggregate = await _eventStore.LoadAggregateAsync <TAggregate, TIdentity>(command.AggregateId, c).ConfigureAwait(false);
                if (aggregate.HasSourceId(command.SourceId))
                {
                    throw new DuplicateOperationException(
                        command.SourceId,
                        aggregate.Id,
                        $"Aggregate '{aggregate.GetType().PrettyPrint()}' has already had operation '{command.SourceId}' performed. New source is '{command.GetType().PrettyPrint()}'");
                }

                await commandExecutionDetails.Invoker(commandHandler, aggregate, command, c).ConfigureAwait(false);
                return await aggregate.CommitAsync(_eventStore, command.SourceId, c).ConfigureAwait(false);
            },
                       Label.Named($"command-execution-{commandType.Name.ToLowerInvariant()}"),
                       cancellationToken));
        }
Пример #20
0
        public async Task PublishAsync <TEvent>(TEvent @event) where TEvent : IEvent
        {
            if (@event == null)
            {
                throw new ArgumentNullException(nameof(@event));
            }

            var eventHandlers = _resolver.ResolveAll <IEventHandlerAsync <TEvent> >();

            foreach (var handler in eventHandlers)
            {
                await handler.HandleAsync(@event);
            }
        }
Пример #21
0
        private IReadOnlyCollection <IReadModelStore> ResolveReadModelStores(
            Type readModelType)
        {
            var readModelStoreType = typeof(IReadModelStore <>).MakeGenericType(readModelType);
            var readModelStores    = _resolver.ResolveAll(readModelStoreType)
                                     .Select(s => (IReadModelStore)s)
                                     .ToList();

            if (!readModelStores.Any())
            {
                throw new ArgumentException($"Could not find any read stores for read model '{readModelType.PrettyPrint()}'");
            }

            return(readModelStores);
        }
Пример #22
0
        public async ValueTask Publish <TEvent>(TEvent @event, CancellationToken cancellationToken = default) where TEvent : IEvent
        {
            await _metrics.Counter(@event, cancellationToken).ConfigureAwait(false);

            var handlers = _resolver.ResolveAll <IEventHandler <TEvent> >();

            foreach (var handler in handlers)
            {
                await handler.Handle(@event).ConfigureAwait(false);
            }

            if (@event is IBusMessage message)
            {
                await _bus.Publish(@event, cancellationToken).ConfigureAwait(false);
            }
        }
Пример #23
0
        /// <inheritdoc />
        public void Publish <TEvent>(TEvent @event) where TEvent : IEvent
        {
            if (@event == null)
            {
                throw new ArgumentNullException(nameof(@event));
            }

            var handlers = _resolver.ResolveAll <IEventHandler <TEvent> >();

            foreach (var handler in handlers)
            {
                handler.Handle(@event);
            }

            //if (@event is IBusMessage message)
            //    _busMessageDispatcher.DispatchAsync(message).GetAwaiter().GetResult();
        }
Пример #24
0
        private Task <IReadOnlyCollection <IDomainEvent> > ExecuteCommandAsync <TAggregate, TIdentity>(
            ICommand <TAggregate, TIdentity> command,
            CancellationToken cancellationToken)
            where TAggregate : IAggregateRoot <TIdentity>
            where TIdentity : IIdentity
        {
            var aggregateType      = typeof(TAggregate);
            var identityType       = typeof(TIdentity);
            var commandType        = command.GetType();
            var commandHandlerType = typeof(ICommandHandler <, ,>).MakeGenericType(aggregateType, identityType, commandType);

            var commandHandlers = _resolver.ResolveAll(commandHandlerType).ToList();

            if (!commandHandlers.Any())
            {
                throw new NoCommandHandlersException(string.Format(
                                                         "No command handlers registered for the command '{0}' on aggregate '{1}'",
                                                         commandType.Name,
                                                         aggregateType.Name));
            }
            if (commandHandlers.Count > 1)
            {
                throw new InvalidOperationException(string.Format(
                                                        "Too many command handlers the command '{0}' on aggregate '{1}'. These were found: {2}",
                                                        commandType.Name,
                                                        aggregateType.Name,
                                                        string.Join(", ", commandHandlers.Select(h => h.GetType().Name))));
            }
            var commandHandler = commandHandlers.Single();

            var commandInvoker = commandHandlerType.GetMethod("ExecuteAsync");

            return(_transientFaultHandler.TryAsync(
                       async c =>
            {
                var aggregate = await _eventStore.LoadAggregateAsync <TAggregate, TIdentity>(command.Id, c).ConfigureAwait(false);

                var invokeTask = (Task)commandInvoker.Invoke(commandHandler, new object[] { aggregate, command, c });
                await invokeTask.ConfigureAwait(false);

                return await aggregate.CommitAsync(_eventStore, c).ConfigureAwait(false);
            },
                       Label.Named(string.Format("command-execution-{0}", commandType.Name.ToLowerInvariant())),
                       cancellationToken));
        }
Пример #25
0
        private IEnumerable <IDomainEvent> Upgrade(IEnumerable <IDomainEvent> domainEvents)
        {
            var domainEventList = domainEvents.ToList();

            if (!domainEventList.Any())
            {
                return(Enumerable.Empty <IDomainEvent>());
            }

            var eventUpgraders = domainEventList
                                 .Select(d => d.AggregateType)
                                 .Distinct()
                                 .ToDictionary(
                t => t,
                t =>
            {
                var cache     = GetCache(t);
                var upgraders = _resolver.ResolveAll(cache.EventUpgraderType).OrderBy(u => u.GetType().Name).ToList();
                return(new
                {
                    EventUpgraders = upgraders,
                    cache.Upgrade
                });
            });

            if (!eventUpgraders.Any())
            {
                return(Enumerable.Empty <IDomainEvent>());
            }

            _log.Verbose(() => string.Format(
                             "Upgrading {0} events and found these event upgraders to use: {1}",
                             domainEventList.Count,
                             string.Join(", ", eventUpgraders.Values.SelectMany(a => a.EventUpgraders.Select(e => e.GetType().PrettyPrint())))));

            return(domainEventList
                   .SelectMany(e =>
            {
                var a = eventUpgraders[e.AggregateType];
                return a.EventUpgraders.Aggregate(
                    (IEnumerable <IDomainEvent>) new[] { e },
                    (de, up) => de.SelectMany(ee => a.Upgrade(up, ee)));
            })
                   .OrderBy(d => d.AggregateSequenceNumber));
        }
Пример #26
0
        public Task PurgeAsync(
            Type readModelType,
            CancellationToken cancellationToken)
        {
            var readModelStoreType = typeof(IReadModelStore <>).MakeGenericType(readModelType);

            var readModelStores = _resolver.ResolveAll(readModelStoreType)
                                  .Select(s => (IReadModelStore)s)
                                  .ToList();

            if (!readModelStores.Any())
            {
                throw new ArgumentException($"Could not find any read stores for read model '{readModelType.PrettyPrint()}'");
            }

            var deleteTasks = readModelStores.Select(s => s.DeleteAllAsync(cancellationToken));

            return(Task.WhenAll(deleteTasks));
        }
Пример #27
0
        private async Task <IReadOnlyCollection <IDomainEvent> > ExecuteCommandAsync
        <TAggregate, TIdentity, TSourceIdentity>(
            ICommand <TAggregate, TIdentity, TSourceIdentity> command,
            CancellationToken cancellationToken)
            where TAggregate : IAggregateRoot <TIdentity>
            where TIdentity : IIdentity
            where TSourceIdentity : ISourceId
        {
            var commandType             = command.GetType();
            var commandExecutionDetails =
                await GetCommandExecutionDetailsAsync(commandType, cancellationToken).ConfigureAwait(false);

            var commandHandlers = _resolver.ResolveAll(commandExecutionDetails.CommandHandlerType)
                                  .Cast <ICommandHandler>()
                                  .ToList();

            if (!commandHandlers.Any())
            {
                throw new NoCommandHandlersException(string.Format(
                                                         "No command handlers registered for the command '{0}' on aggregate '{1}'",
                                                         commandType.PrettyPrint(),
                                                         typeof(TAggregate).PrettyPrint()));
            }
            if (commandHandlers.Count > 1)
            {
                throw new InvalidOperationException(string.Format(
                                                        "Too many command handlers the command '{0}' on aggregate '{1}'. These were found: {2}",
                                                        commandType.PrettyPrint(),
                                                        typeof(TAggregate).PrettyPrint(),
                                                        string.Join(", ", commandHandlers.Select(h => h.GetType().PrettyPrint()))));
            }

            var commandHandler = commandHandlers.Single();

            return(await _aggregateStore.UpdateAsync <TAggregate, TIdentity>(
                       command.AggregateId,
                       command.SourceId,
                       (a, c) => commandExecutionDetails.Invoker(commandHandler, a, command, c),
                       cancellationToken)
                   .ConfigureAwait(false));
        }
Пример #28
0
 /// <summary>
 /// Resolves all instances of the given type.
 /// </summary>
 /// <typeparam name="T">The type to resolve.</typeparam>
 /// <returns>All instances of the given type.</returns>
 public static IList <T> ResolveAll <T>()
     where T : class
 {
     return(currentResolver.ResolveAll <T>());
 }
Пример #29
0
 public static IEnumerable <T> ResolveAll <T>()
 {
     return(_resolver.ResolveAll <T>());
 }
Пример #30
0
 public static IEnumerable <object> GetAll(this IResolver resolver, Type type)
 {
     return((object[])ResolverHelper.ConvertArray(type, resolver.ResolveAll(type, null)));
 }