public IAggregate CreateFrom(DomainEvent @event)
        {
            IAggregate aggregate = null;
            Func<IAggregate> factory;

            var isCreationEvent = factoryMethods.TryGetValue(@event.GetType(), out factory);

            if (isCreationEvent)
            {
                aggregate = factory();
                aggregate.ApplyEvent(@event);
            }

            return aggregate;
        }
Esempio n. 2
0
        public void Send(DomainEvent @event)
        {
            foreach (var registration in componentContext.ComponentRegistry.Registrations) {
                foreach (var service in registration.Services.OfType<TypedService>()) {
                    var type = service.ServiceType;
                    if (!type.IsInterface || !type.IsGenericType || !type.IsConstructedGenericType ||
                        type.GetGenericTypeDefinition() != typeof (IHandleDomainEvents<>)) {
                        continue;
                    }

                    var method = type.GetMethod("Handle");

                    if (Enumerable.Any<ParameterInfo>(method.GetParameters(), x => x.ParameterType == @event.GetType())) {
                        var handler = componentContext.ResolveComponent(registration, new List<Parameter>());
                        method.Invoke(handler, new[] {@event});
                    }
                }
            }
        }
        private void InnerDispatch(DomainEvent @event)
        {
            var executors = _catalog.GetAllHandlerFor(@event.GetType());

            foreach (var executor in executors)
            {
                try
                {
                    if (_logger.IsDebugEnabled) _logger.Debug("Dispatching event " + @event.GetType() + " to the handler " + executor.DefiningType + "." + executor.Invoker.Method.Name);
                    executor.Invoke(@event);
                    if (_logger.IsDebugEnabled) _logger.Debug("Dispatched event " + @event.GetType() + " to the handler " + executor.DefiningType + "." + executor.Invoker.Method.Name);
                }
                catch (OutOfMemoryException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    _logger.Error("Error during dispatching event " + @event.GetType() + " to the handler " + executor.DefiningType + "." + executor.Invoker.Method.Name, ex);
                }
            }
        }
        /// <summary>
        /// Dispatches the given domain event to the view instance. The view instance's <see cref="IViewInstance.LastGlobalSequenceNumber"/>
        /// will automatically be updated after successful dispatch. If the global sequence number of the event is lower or equal to the
        /// view instance's <see cref="IViewInstance.LastGlobalSequenceNumber"/>, the event is ignored.
        /// </summary>
        public void DispatchToView(IViewContext context, DomainEvent domainEvent, TViewInstance view)
        {
            var lastGlobalSequenceNumber = domainEvent.GetGlobalSequenceNumber();

            if (lastGlobalSequenceNumber <= view.LastGlobalSequenceNumber)
            {
                return;
            }

            var domainEventType = domainEvent.GetType();

            var dispatcherMethod = _dispatcherMethods
                                   .GetOrAdd(domainEventType, type => _dispatchToViewGenericMethod.MakeGenericMethod(domainEventType));

            try
            {
                var viewId = view.Id;

                _logger.Debug("Dispatching event {0} to {1} with ID {2}", lastGlobalSequenceNumber, view, viewId);

                context.CurrentEvent = domainEvent;

                dispatcherMethod.Invoke(this, new object[] { context, domainEvent, view });

                view.Id = viewId;
                view.LastGlobalSequenceNumber = lastGlobalSequenceNumber;
            }
            catch (TargetInvocationException exception)
            {
                throw new ApplicationException(string.Format("Could not dispatch {0} to {1}", domainEvent, view), exception.InnerException);
            }
            catch (Exception exception)
            {
                throw new ApplicationException(string.Format("Could not dispatch {0} to {1}", domainEvent, view), exception);
            }
        }
 public async Task Publish(DomainEvent domainEvent)
 {
     _logger.LogInformation("Publishing domain event. Event - {event}", domainEvent.GetType().Name);
     await _mediator.Publish(GetNotificationCorrespondingToDomainEvent(domainEvent));
 }
 public bool CanMap(DomainEvent @event)
 {
     return(@event.GetType() == typeof(AccommodationLeadCreated));
 }
Esempio n. 7
0
        private static IDomainEventMessage CreateDomainEventMessage(DomainEvent domainEvent)
        {
            var domainEventMessageType = typeof(DomainEventMessage <>).MakeGenericType(domainEvent.GetType());
            var message = (IDomainEventMessage)Activator.CreateInstance(domainEventMessageType);

            message.DomainEvent = domainEvent;
            return(message);
        }
 public void RegisterTimeSpent(IViewManager viewManager, DomainEvent domainEvent, TimeSpan duration)
 {
     TimeSpent.GetOrAdd(viewManager, vm => new ConcurrentDictionary <Type, TimeSpan>())
     .AddOrUpdate(domainEvent.GetType(), type => duration, (type, existing) => existing + duration);
 }
Esempio n. 9
0
    private static dynamic CreateDynamicEvent(DomainEvent domainEvent)
    {
        var type = typeof(AfterCommittedEvent <>).MakeGenericType(domainEvent.GetType());

        return(Activator.CreateInstance(type, domainEvent));
    }
Esempio n. 10
0
 private string FormatCollectionWrapperExceptionMessage(string message, DomainEvent evt)
 {
     if (evt == null)
     {
         return($"CollectionWrapper [{typeof(TModel).Name}] - {message}");
     }
     else
     {
         return($"CollectionWrapper [{typeof(TModel).Name}] Event Position [{evt.CheckpointToken}] Event Type [{evt.GetType().Name}]- {message}");
     }
 }
 public bool IsCreationEvent(DomainEvent @event)
 {
     return factoryMethods.ContainsKey(@event.GetType());
 }
        public void Add(DomainEvent @event)
        {
            var eventToAdd = new Event(Guid.NewGuid(), @event.GetType().Name, Newtonsoft.Json.JsonConvert.SerializeObject(@event));

            _events.Add(eventToAdd);
        }
Esempio n. 13
0
 public bool CanMap(DomainEvent @event)
 {
     return(@event.GetType() == typeof(AuthenticationCreated));
 }
 private static Type CreateEventHandlerTypeFor(DomainEvent domainEvent) =>
 typeof(DomainEventHandler <>).MakeGenericType(domainEvent.GetType());
Esempio n. 15
0
            public void Publish(DomainEvent domainEvent)
            {
                var exceptionList = new List <Exception>();

                var handleMethod = typeof(IHandleDomainEvents <>).MakeGenericType(domainEventType).GetMethod("Handle");

                foreach (var eventHandlerType in eventHandlerTypes)
                {
                    try
                    {
                        var eventHandler = eventHandlerFactory.Create(eventHandlerType);
                        handleMethod.Invoke(eventHandler, new object[] { domainEvent });
                    }
                    catch (Exception exception)
                    {
                        logger.Error(string.Format("An exception occured while handling event of type '{0}'\nMessage: {1}", domainEvent.GetType(), exception.Message), exception);
                        exceptionList.Add(exception);
                    }
                }

                if (exceptionList.Count > 0)
                {
                    throw new AggregateException(exceptionList);
                }
            }
Esempio n. 16
0
        private void ApplyChange(DomainEvent domainEvent, bool isNew)
        {
            var method = GetType().GetMethod("Apply", BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { domainEvent.GetType() }, null);

            if (method == null)
            {
                throw new InvalidOperationException("Apply method not found");
            }
            method.Invoke(this, new[] { domainEvent });
            if (isNew)
            {
                _changes.Add(domainEvent);
            }
        }
        internal void DispatchEvent(DomainEvent evt)
        {
            var chkpoint = evt.CheckpointToken;

            if (chkpoint > LastCheckpointDispatched)
            {
                if (_logger.IsDebugEnabled)
                {
                    _logger.DebugFormat("Discharded event {0} commit {1} because last checkpoint dispatched for slot {2} is {3}.", evt.CommitId, evt.CheckpointToken, SlotName, _maxCheckpointDispatched);
                }
                return;
            }

            Interlocked.Increment(ref RebuildProjectionMetrics.CountOfConcurrentDispatchingCommit);

            //Console.WriteLine("[{0:00}] - Slot {1}", Thread.CurrentThread.ManagedThreadId, slotName);
            if (_logger.IsDebugEnabled)
            {
                _logger.ThreadProperties["commit"] = evt.CommitId;
                _logger.DebugFormat("Dispatching checkpoit {0} on tenant {1}", evt.CheckpointToken, _config.TenantId);
            }

            TenantContext.Enter(_config.TenantId);

            try
            {
                if (_logger.IsDebugEnabled)
                {
                    _logger.ThreadProperties["evType"]            = evt.GetType().Name;
                    _logger.ThreadProperties["evMsId"]            = evt.MessageId;
                    _logger.ThreadProperties["evCheckpointToken"] = evt.CheckpointToken;
                }
                string eventName = evt.GetType().Name;
                foreach (var projection in _projections)
                {
                    var cname = projection.GetCommonName();
                    if (_logger.IsDebugEnabled)
                    {
                        _logger.ThreadProperties["prj"] = cname;
                    }

                    bool handled;
                    long ticks = 0;

                    try
                    {
                        //pay attention, stopwatch consumes time.
                        var sw = new Stopwatch();
                        sw.Start();
                        handled = projection.Handle(evt, true);
                        sw.Stop();
                        ticks = sw.ElapsedTicks;
                        MetricsHelper.IncrementProjectionCounterRebuild(cname, SlotName, eventName, ticks);
                    }
                    catch (Exception ex)
                    {
                        _logger.FatalFormat(ex, "[Slot: {3} Projection: {4}] Failed checkpoint: {0} StreamId: {1} Event Name: {2}",
                                            evt.CheckpointToken,
                                            evt.AggregateId,
                                            eventName,
                                            SlotName,
                                            cname
                                            );
                        throw;
                    }

                    _metrics.Inc(cname, eventName, ticks);

                    if (_logger.IsDebugEnabled)
                    {
                        _logger.DebugFormat("[{3}] [{4}] Handled checkpoint {0}: {1} > {2}",
                                            evt.CheckpointToken,
                                            evt.AggregateId,
                                            eventName,
                                            SlotName,
                                            cname
                                            );
                    }

                    if (_logger.IsDebugEnabled)
                    {
                        _logger.ThreadProperties["prj"] = null;
                    }
                }

                ClearLoggerThreadPropertiesForEventDispatchLoop();
            }
            catch (Exception ex)
            {
                _logger.ErrorFormat(ex, "Error dispathing commit id: {0}\nMessage: {1}\nError: {2}",
                                    evt.CheckpointToken, evt, ex.Message);
                ClearLoggerThreadPropertiesForEventDispatchLoop();
                throw;
            }
            _lastCheckpointRebuilded = chkpoint;
            if (_logger.IsDebugEnabled)
            {
                _logger.ThreadProperties["commit"] = null;
            }
            Interlocked.Decrement(ref RebuildProjectionMetrics.CountOfConcurrentDispatchingCommit);
        }
        private PollingClient2.HandlingResult ErrorHandler(DomainEvent evt, Exception ex)
        {
            var builder = _serviceProvider.GetRequiredService <IHandlerResolver>();

            if (builder.TryGetErrorHandler(out var handler) && (bool)handler.DynamicInvoke(evt, ex))
            {
                _logger.LogError(ex, "Error during handling {EventType}. Will retry.", evt.GetType());
                return(PollingClient2.HandlingResult.Retry);
            }

            _logger.LogCritical(ex, "Error during handling {EventType}. Exit polling.", evt.GetType());
            _checkpointLoader.SaveAsync(_currentCheckpoint).GetAwaiter().GetResult();
            return(PollingClient2.HandlingResult.Stop);
        }
Esempio n. 19
0
 public IEventPublisher CreatePublisher(DomainEvent @event)
 {
     return(_publishers[@event.GetType()]);
 }
Esempio n. 20
0
        /// <summary>
        /// Emits the given domain event, adding the aggregate root's <see cref="Id"/> and a sequence number to its metadata, along with some type information
        /// </summary>
        protected void Emit <TAggregateRoot>(DomainEvent <TAggregateRoot> e) where TAggregateRoot : AggregateRoot
        {
            if (e == null)
            {
                throw new ArgumentNullException("e", "Can't emit null!");
            }

            if (string.IsNullOrWhiteSpace(Id))
            {
                throw new InvalidOperationException(
                          string.Format(
                              "Attempted to emit event {0} from aggregate root {1}, but it has not yet been assigned an ID!",
                              e, GetType()));
            }

            var eventType = e.GetType();

            var emitterInterface = typeof(IEmit <>).MakeGenericType(eventType);

            if (!emitterInterface.IsAssignableFrom(GetType()))
            {
                throw new InvalidOperationException(
                          string.Format(
                              "Attempted to emit event {0} but the aggregate root {1} does not implement IEmit<{2}>",
                              e, GetType().Name, e.GetType().Name));
            }

            if (UnitOfWork == null)
            {
                throw new InvalidOperationException(string.Format("Attempted to emit event {0}, but the aggreate root does not have a unit of work!", e));
            }

            if (ReplayState != ReplayState.None)
            {
                throw new InvalidOperationException(string.Format("Attempted to emit event {0}, but the aggreate root's replay state is {1}! - events can only be emitted when the root is not applying events", e, ReplayState));
            }

            if (!typeof(TAggregateRoot).IsAssignableFrom(GetType()))
            {
                throw new InvalidOperationException(
                          string.Format("Attempted to emit event {0} which is owned by {1} from aggregate root of type {2}",
                                        e, typeof(TAggregateRoot), GetType()));
            }

            var now            = Time.UtcNow();
            var sequenceNumber = CurrentSequenceNumber + 1;

            e.Meta.Merge(CurrentCommandMetadata ?? new Metadata());
            e.Meta[DomainEvent.MetadataKeys.AggregateRootId] = Id;
            e.Meta[DomainEvent.MetadataKeys.TimeUtc]         = now.ToString("u");
            e.Meta[DomainEvent.MetadataKeys.SequenceNumber]  = sequenceNumber.ToString(Metadata.NumberCulture);

            e.Meta.TakeFromAttributes(eventType);
            e.Meta.TakeFromAttributes(GetType());

            try
            {
                ApplyEvent(e, ReplayState.EmitApply);
            }
            catch (Exception exception)
            {
                throw new ApplicationException(string.Format(@"Could not apply event {0} to {1} - please check the inner exception, and/or make sure that the aggregate root type is PUBLIC", e, this), exception);
            }

            UnitOfWork.AddEmittedEvent(this, e);
            EventEmitted(e);
        }
Esempio n. 21
0
 public void RegisterTimeSpent(IViewManager viewManager, DomainEvent domainEvent, TimeSpan duration)
 {
     _timeSpent.GetOrAdd(viewManager, vm => new ConcurrentDictionary <Type, Tracking>())
     .AddOrUpdate(domainEvent.GetType(), type => new Tracking(duration), (type, tracking) => tracking.Update(duration));
 }
Esempio n. 22
0
        private IEnumerable GetEventHandlers(DomainEvent @event)
        {
            var domainEventHandlerType = typeof(IDomainEventHandler <>).MakeGenericType(@event.GetType());
            var allEventHandlers       = typeof(IEnumerable <>).MakeGenericType(domainEventHandlerType);

            return((IEnumerable)_serviceProvider.GetService(allEventHandlers));
        }
 public string Serialize(DomainEvent domainEvent)
 {
     return(JsonSerializer.SerializeToString(domainEvent, domainEvent.GetType()));
 }
 public string ForClass(DomainEvent domainEvent)
 {
     return(IndexedDomainEvents.FirstOrDefault(x => x.Value.Equals(domainEvent.GetType())).Key);
 }
Esempio n. 25
0
 public bool CanMap(DomainEvent @event)
 {
     return(@event.GetType() == typeof(UserCreated));
 }
        public IEnumerable <SubscriptionInfo> GetHandlersForEvent(DomainEvent domainEvent)
        {
            var key = GetEventKey(domainEvent.GetType());

            return(GetHandlersForEvent(key));
        }
Esempio n. 27
0
 static void onLog(DomainEvent avisadoEstas)
 {
     Console.WriteLine($"LOG => {DateTime.UtcNow} Evento capturado {avisadoEstas.OccuredOn} - Type {avisadoEstas.GetType()}");
 }
 private INotification GetNotificationCorrespondingToDomainEvent(DomainEvent domainEvent)
 {
     return((INotification)Activator.CreateInstance(
                typeof(DomainEventNotification <>).MakeGenericType(domainEvent.GetType()), domainEvent));
 }
Esempio n. 29
0
 public async Task Publish(DomainEvent domainEvent)
 {
     _logger.LogInformation(PublishInformationMessage, domainEvent.GetType().Name);
     await _mediator.Publish(GetNotificationCorrespondingToDomainEvent(domainEvent));
 }