public CommandHandler(CentralValidations validator, IUnityOfWork unityOfWork, ICommandRepository commandRepository, DomainEventBus eventBus)
 {
     _validator         = validator;
     _uoW               = unityOfWork;
     _commandRepository = commandRepository;
     _eventBus          = eventBus;
 }
Ejemplo n.º 2
0
        public void GetHandlersGetsAllHandlers()
        {
            var container = GetContainer();
            var sut       = new DomainEventBus(container);

            Assert.That(sut.GetHandlers <Event1>().Count, Is.EqualTo(2));
        }
Ejemplo n.º 3
0
        public Result Create(OrderRequest orderRequest)
        {
            if (!string.IsNullOrWhiteSpace(orderRequest.CouponId))
            {
                var couponResult = DomainRegistry.SellingPriceService().IsCouponCanUse(orderRequest.CouponId, orderRequest.OrderTime);
                if (!couponResult.IsSuccess)
                {
                    return(Result.Fail(couponResult.Msg));
                }
            }

            var orderId = DomainRegistry.OrderRepository().NextIdentity();
            var order   = Domain.Order.Aggregate.Order.Create(orderId, orderRequest.UserId, orderRequest.Receiver,
                                                              orderRequest.CountryId, orderRequest.CountryName, orderRequest.ProvinceId, orderRequest.ProvinceName,
                                                              orderRequest.CityId, orderRequest.CityName, orderRequest.DistrictId, orderRequest.DistrictName,
                                                              orderRequest.Address, orderRequest.Mobile, orderRequest.Phone, orderRequest.Email,
                                                              orderRequest.PaymentMethodId, orderRequest.PaymentMethodName, orderRequest.ExpressId,
                                                              orderRequest.ExpressName, orderRequest.Freight, orderRequest.CouponId, orderRequest.CouponName, orderRequest.CouponValue, orderRequest.OrderTime);

            foreach (var orderItemRequest in orderRequest.OrderItems)
            {
                order.AddOrderItem(orderItemRequest.ProductId, orderItemRequest.Quantity, orderItemRequest.UnitPrice, orderItemRequest.JoinedMultiProductsPromotionId, orderItemRequest.ProductName);
            }

            DomainRegistry.OrderRepository().Save(order);
            DomainEventBus.Instance().Publish(new OrderCreated(order.ID, order.UserId, order.Receiver));
            return(Result.Success());
        }
Ejemplo n.º 4
0
        public async Task Save(TAggregateRoot aggregateRoot)
        {
            // Check for concurrency issues
            await ConcurrencyCheck(aggregateRoot);

            // Persist Events
            foreach (var uncommittedEvent in aggregateRoot.UncommittedEvents)
            {
                TEventSet @event = (TEventSet)Activator.CreateInstance(typeof(TEventSet), uncommittedEvent);
                await Client.CreateDocumentAsync(_databaseCollectionUri, @event);
            }

            // Check if snapshot is required
            bool snapshotRequired = CanProcessSnapshots &&
                                    aggregateRoot.UncommittedEvents.Any(
                eventWrapper => eventWrapper.Sequence % SnapshotRepository.SnapshotInterval == 0
                );

            if (snapshotRequired)
            {
                await SnapshotRepository.SaveSnapshot(aggregateRoot);
            }

            // Publish events if possible
            if (CanPublishEvents)
            {
                foreach (var uncommittedEvent in aggregateRoot.UncommittedEvents)
                {
                    await DomainEventBus.Publish(uncommittedEvent.Event);
                }
            }

            // Mark aggregate root as committed
            aggregateRoot.MarkAsCommitted();
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Remove
 /// </summary>
 public virtual void Remove()
 {
     repository.Remove((T)this);
     DomainEventBus.Publish(new DefaultAggregationRemoveDomainEvent <T>()
     {
         Object = this as T
     });
 }
Ejemplo n.º 6
0
        public static Order Create(string id, string userId, string receiver, string countryId, string countryName, string provinceId, string provinceName, string cityId, string cityName, string districtId, string districtName, string address, string mobile, string phone, string email, string paymentMethodId, string paymentMethodName, string expressId, string expressName, decimal freight, string couponId, string couponName, decimal couponValue, DateTime orderTime)
        {
            var order = new Order(id, userId, receiver, countryId, countryName, provinceId, provinceName, cityId, cityName, districtId, districtName, address, mobile, phone, email, paymentMethodId, paymentMethodName, expressId, expressName, freight, couponId, couponName, couponValue, orderTime, default(DateTime));

            DomainEventBus.Instance().Publish(new OrderCreated(order.ID, order.UserId, order.Receiver));

            return(order);
        }
Ejemplo n.º 7
0
 public DefaultEventStore(EventPersistence persistence,
                          DomainEventBus domainEventBus,
                          DomainEventSerializer serializer)
 {
     _persistence    = persistence;
     _domainEventBus = domainEventBus;
     _serializer     = serializer;
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Remove
        /// </summary>
        public virtual async Task RemoveAsync()
        {
            await repository.RemoveAsync((T)this).ConfigureAwait(false);

            DomainEventBus.Publish(new DefaultAggregationRemoveDomainEvent <T>()
            {
                Object = this as T
            });
        }
        public static void Initialize()
        {
            var types = Assembly.Load("Mall.Domain.Order.DomainEventSubscribers").GetTypes().Where(ent => !ent.IsGenericType && ent.GetInterface(typeof(IDomainEventSubscriber).FullName) != null).ToList();

            foreach (var type in types)
            {
                var subscriberInstance = Activator.CreateInstance(AppDomain.CurrentDomain, type.Assembly.FullName, type.FullName).Unwrap();
                var subscriber         = (IDomainEventSubscriber)subscriberInstance;
                DomainEventBus.Instance().Subscribe(subscriber);
            }
        }
 public CreateUserCommand(
     string name,
     string password,
     string email,
     string login,
     IUserRepository repository,
     CentralValidations centralValidations,
     DomainEventBus eventBus)
 {
     _repository         = repository;
     _centralValidations = centralValidations;
     eventBus            = _eventBus;
 }
Ejemplo n.º 11
0
        public void GetHandlersHasCorrectPriortyOrder()
        {
            var container = GetContainer();
            var utilities = new DomainEventBus(container);
            var sut       = utilities.GetHandlers <Event2>();

            Assert.That(sut.Count, Is.EqualTo(4));

            Assert.That(sut[0].GetType(), Is.EqualTo(typeof(Event2Handler2)), "Negative priority should be first");
            Assert.That(sut[1].GetType(), Is.EqualTo(typeof(Event2Handler3)), "Zero priority should be second");
            Assert.That(sut[2].GetType(), Is.EqualTo(typeof(Event2Handler1)), "Positive priority should be third");
            Assert.That(sut[3].GetType(), Is.EqualTo(typeof(Event2Handler4)), "Default priority (100) should be last");
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Save
        /// </summary>
        public virtual Result <T> Save()
        {
            var saveData = repository.Save(this as T);

            if (saveData == null)
            {
                return(Result <T> .FailedResult("Data saved failed"));
            }
            DomainEventBus.Publish(new DefaultAggregationSaveDomainEvent <T>()
            {
                Object = saveData
            });
            return(Result <T> .SuccessResult("Data saved successfully", "", saveData));
        }
Ejemplo n.º 13
0
        public void WhenHandlerRegisteredForBaseType_ThenHandlesOnRaise()
        {
            var args = new FooArgs {
                Id = 5
            };
            var handler = new Mock <DomainEventHandler <int, BaseArgs> > {
                CallBase = true
            };

            var bus = new DomainEventBus <int>(new[] { handler.Object });

            bus.Publish(new TestAggregate(), args);

            handler.Verify(x => x.Handle(5, It.IsAny <BaseArgs>()));
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Remove
        /// </summary>
        public virtual Result Remove()
        {
            if (IdentityValueIsNone())
            {
                throw new EZNEWException("The object does not have an identity value set and cannot perform a remove");
            }
            T removeData = this as T;

            repository.Remove(removeData);
            DomainEventBus.Publish(new DefaultAggregationRemoveDomainEvent <T>()
            {
                Object = removeData
            });
            return(Result.SuccessResult("Data removed successfully"));
        }
Ejemplo n.º 15
0
        public void WhenAsyncHandlerRegisteredForSpecificType_ThenCanUseDefaultAsynRunner()
        {
            var args = new FooArgs {
                Id = 5
            };
            var handler = new Mock <DomainEventHandler <int, FooArgs> > {
                CallBase = true
            };

            handler.Setup(x => x.IsAsync).Returns(true);

            var bus = new DomainEventBus <int>(new[] { handler.Object });

            bus.Publish(new TestAggregate(), args);

            handler.Verify(x => x.Handle(5, args), Times.Never());
        }
Ejemplo n.º 16
0
        public void WhenHandlerRegistered_ThenCanProcessEntity()
        {
            var product = new Product {
                Title = "DevStore"
            };
            var context = default(DomainContext);
            var bus     = default(IDomainEventBus);

            bus = new DomainEventBus(new IDomainEventHandler[]
            {
                new ConsoleHandler(),
                new SendMailHandler(new Lazy <DomainContext>(() => context), new Lazy <IDomainEventBus>(() => bus)),
            });

            context = new DomainContext(bus, product);

            product.Publish(1);

            context.SaveChanges();
        }
Ejemplo n.º 17
0
        public void WhenAsyncHandlerRegisteredForSpecificType_ThenInvokesAsyncRunner()
        {
            var args = new FooArgs {
                Id = 5
            };
            var handler = new Mock <DomainEventHandler <int, FooArgs> > {
                CallBase = true
            };

            handler.Setup(x => x.IsAsync).Returns(true);
            var             asyncCalled = false;
            Action <Action> asyncRunner = action => asyncCalled = true;

            var bus = new DomainEventBus <int>(new[] { handler.Object }, asyncRunner);

            bus.Publish(new TestAggregate(), args);

            handler.Verify(x => x.Handle(5, args), Times.Never());
            Assert.True(asyncCalled);
        }
Ejemplo n.º 18
0
        internal static void Init()
        {
            #region 保存用户数据

            #region 刷新登录缓存信息

            DomainEventBus.GlobalSubscribe <DefaultAggregationSaveDomainEvent <User> >(e =>
            {
                if (e?.Object != null && e.Object.Status != UserStatus.正常)
                {
                    Task.Run(() =>
                    {
                        var userId            = e.Object.SysNo.ToString();
                        var loginUserCacheKey = new CacheKey("LoginUser", userId);
                        CacheManager.Keys.Delete(new Cache.Keys.Request.DeleteOption()
                        {
                            Keys = new List <CacheKey>(1)
                            {
                                loginUserCacheKey
                            }
                        });
                        var loginRecordCacheKey = new CacheKey("AllLoginUser");
                        CacheManager.Set.Remove(new Cache.Set.Request.SetRemoveOption()
                        {
                            Key          = loginRecordCacheKey,
                            RemoveValues = new List <string>(1)
                            {
                                userId
                            }
                        });
                    });
                }
                return(DomainEventExecuteResult.EmptyResult());
            }, EventTriggerTime.WorkCompleted);

            #endregion

            #endregion
        }
        public virtual void Save(TAggregateRoot aggregateRoot)
        {
            var set = Context.Set <TEventSet>();

            //Check for concurrency issues
            ConcurrencyCheck <TAggregateRoot, TEventSet> .Process(aggregateRoot, set);

            //Persist Events
            foreach (var uncommittedEvent in aggregateRoot.UncommittedEvents)
            {
                var @event = CreateDomainEventRecord(uncommittedEvent);
                PersistedEvents.Add(@event);
            }

            //Check if snapshot is required
            var snapshotRequired = CanProcessSnapshots &&
                                   aggregateRoot.UncommittedEvents.Any(
                e => e.Sequence % SnapshotRepository.SnapshotInterval == 0);

            if (snapshotRequired)
            {
                SnapshotRepository.SaveSnapshot(aggregateRoot);
            }

            Context.SaveChanges();

            //Publish events if possible
            if (CanPublishEvents)
            {
                foreach (var uncommittedEvent in aggregateRoot.UncommittedEvents)
                {
                    DomainEventBus.Publish(uncommittedEvent.Event);
                }
            }

            //Mark aggregate root as committed
            aggregateRoot.MarkAsCommitted();
        }
Ejemplo n.º 20
0
 public ApplicationServer(IApplicationRepository applicationRepository, DomainEventBus eventBus)
 {
     _applicationRepository = applicationRepository;
     _eventBus = eventBus;
 }
Ejemplo n.º 21
0
 public DefaultEventStore(EventPersistence persistence, DomainEventBus domainEventBus)
     : this(persistence, domainEventBus, new JsonDomainEventSerializer())
 {
 }
Ejemplo n.º 22
0
 /// <summary>
 /// 
 /// </summary>
 public AggregateRoot()
 {
     Bus = new DomainEventBus();
 }
 public ProductCreator(ProductRepository productRepository, DomainEventBus eventBus)
 {
     this.productRepository = productRepository;
     this.eventBus          = eventBus;
 }
Ejemplo n.º 24
0
        public void WhenPublishNullEvent_ThenThrows()
        {
            var bus = new DomainEventBus <int>(Enumerable.Empty <DomainEventHandler>());

            Assert.Throws <ArgumentNullException>(() => bus.Publish(new TestAggregate(), default(FooArgs)));
        }
 public CreateProductCommandHandler(ProductRepository productRepository, DomainEventBus eventBus)
 {
     productCreator = new ProductCreator(productRepository, eventBus);
 }
Ejemplo n.º 26
0
        public void WhenPublishNullAggregate_ThenThrows()
        {
            var bus = new DomainEventBus <int>(Enumerable.Empty <DomainEventHandler>());

            Assert.Throws <ArgumentNullException>(() => bus.Publish((AggregateRoot <int>)null, new FooArgs()));
        }