Exemplo n.º 1
0
            public async Task ClearUncommittedEventsFromAggregate(IAggregateRoot <TestAggregate> aggregateRoot,
                                                                  EventStoreRepository sut)
            {
                await sut.SaveAsync(aggregateRoot);

                aggregateRoot.Received(1).ClearUncommittedEvents();
            }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            // docker run --name eventstore-node -it --rm -p 2113:2113 -p 1113:1113 -v ~/data/eventstore/ESData:/var/lib/eventstore -v ~/data/eventstore/logs:/var/log/eventstore eventstore/eventstore --run-projections=all

            Console.WriteLine("Hello EventstoreConsole!");

            var uri = new Uri("tcp://localhost:1113");

            try
            {
                var connection = EventStoreConnection.Create(uri);

                System.Console.WriteLine("Connect to Eventstore...");
                connection.ConnectAsync().Wait();
                System.Console.WriteLine("Connected!");

                var repo = new EventStoreRepository(connection);

                // OrganizationTest(repo);
                WriteByEventType(repo);

                connection.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public async Task GetByIdAsyncWithEventsShouldReturnTheCurrentStateOfTheAggregate()
        {
            //Arrange

            #region mock of DataBaseContext , mock of IDomainEventRebuilder and mock of moqInvoker

            var aggregateId    = Guid.NewGuid();
            var optionsBuilder = new DbContextOptionsBuilder <DataBaseContext>();
            optionsBuilder.UseInMemoryDatabase("FakeInMemoryData");
            var moqContext = new DataBaseContext(optionsBuilder.Options);
            moqContext.Database.EnsureCreated();

            var obj  = new EventOject(aggregateId, "Dupont", "45 av charles degaulle paris, france");
            var type = obj.GetType().AssemblyQualifiedName;
            var json = @"
                {
                    'FullName':'Dupont',
                    'Adresse':'45 av charles degaulle paris, france'
                }";

            moqContext.EventStore.Add(new EventStore(aggregateId,
                                                     1,
                                                     "2@735f8407-16be-44b5-be96-2bab582b5298",
                                                     type,
                                                     DateTime.Now, json));
            moqContext.SaveChanges();

            Mock <IDomainEventRebuilder> moqDomainEventRebuilder = new Mock <IDomainEventRebuilder>();
            moqDomainEventRebuilder.Setup(m => m.RebuildDomainEvents(It.IsAny <IEnumerable <EventStore> >()))
            .Returns(new List <Event>
            {
                obj
            });

            var aggregate = (StubAggregate)typeof(StubAggregate)
                            .GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic,
                                            null,
                                            new Type[0],
                                            new ParameterModifier[0])
                            ?.Invoke(new object[0]);

            var moqInvoker = new Mock <IInvoker <StubAggregate> >();
            moqInvoker.Setup(i => i.CreateInstanceOfAggregateRoot <StubAggregate>()).Returns(aggregate);

            #endregion mock of DataBaseContext , mock of IDomainEventRebuilder and mock of moqInvoker

            var sut = new EventStoreRepository <StubAggregate>(moqContext, moqInvoker.Object, moqDomainEventRebuilder.Object);

            //Act
            var result = await sut.GetByIdAsync <StubAggregate>(aggregateId);

            moqContext.Dispose();

            //Assert
            Assert.NotNull(aggregate);
            Assert.Equal(aggregate, result);
            Assert.Equal(aggregateId, aggregate.Id);
            Assert.Equal(obj.FullName, aggregate.FullName);
            Assert.Equal(obj.Adresse, aggregate.Adresse);
        }
        public ServiceBusRegistry()
        {
            For <IReportingRepository <PatientDto> >()
            .Use <SqlReportingRepository>()
            .Ctor <string>()
            .Is(AppConfig.PatientDBEventStoreEntities);

            var bus = new InProcessBus();

            For <IBus>().Use(bus);

            var eventStore = GetInitializedEventStore(bus);
            var repository = new EventStoreRepository(eventStore, new AggregateFactory(), new ConflictDetector());

            For <IStoreEvents>()
            .Use(eventStore);

            For <IRepository>()
            .Use(repository);

            For <IHandles <CreatePatientCommand> >()
            .Use <CreatePatientCommandHandler>();

            For <IHandles <ChangePatientNameCommand> >()
            .Use <ChangePatientNameCommandHandler>();
        }
Exemplo n.º 5
0
        public static void Main(string[] args)
        {
            var bus = BusSetup.StartWith <Conservative>()
                      .Apply <FlexibleSubscribeAdapter>(a =>
            {
                a.ByInterface(typeof(IEventHandler <>));
                a.ByInterface(typeof(ICommandHandler <>));
            }).Construct();

            var someAwesomeUi = new SomeAwesomeUi(bus);

            using (store = WireupEventStore(bus))
            {
                var repository = new EventStoreRepository(store, new AggregateFactory(), new ConflictDetector());

                var handler  = new CreateAccountCommandHandler(repository);
                var handler2 = new CloseAccountCommandHandler(repository);
                bus.Subscribe(handler);
                bus.Subscribe(handler2);
                bus.Subscribe(new KaChingNotifier());
                bus.Subscribe(new OmgSadnessNotifier());

                someAwesomeUi.CreateNewAccount(AggregateId, "Luiz", "@luizdamim");
                someAwesomeUi.CloseAccount(AggregateId);
            }

            Console.ReadLine();
        }
Exemplo n.º 6
0
        public static EventStoreStatelessActorBuilder <TActor, TRegistry> Create(
            ClusterVNode clusterVNode,
            ConnectionSettings connectionSettings,
            IActorConfiguration actorConfiguration,
            ILoggerFactory?loggerFactory = null,
            Action <IEventStoreRepositoryConfiguration>?getEventStoreRepositoryConfiguration = null)

        {
            var connection = EmbeddedEventStoreConnection.Create(clusterVNode, connectionSettings);

            loggerFactory ??= new DummyLoggerFactory();

            var eventStoreRepositoryConfiguration = new EventStoreRepositoryConfiguration();

            getEventStoreRepositoryConfiguration?.Invoke(eventStoreRepositoryConfiguration);

            var connectionStatusMonitor = new EventStoreConnectionStatusMonitor(connection, loggerFactory);

            var eventStoreRepository = new EventStoreRepository(
                eventStoreRepositoryConfiguration,
                connection,
                connectionStatusMonitor,
                loggerFactory);

            var eventStoreStatelessActorBuilder = new EventStoreStatelessActorBuilder <TActor, TRegistry>(actorConfiguration, eventStoreRepository, connectionStatusMonitor, loggerFactory);

            return(eventStoreStatelessActorBuilder);
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            var eventStoreConfiguration = new EventStoreConfiguration
            {
                MongoDbConnectionString = "mongodb://*****:*****@cluster0-shard-00-00-5pgij.mongodb.net:27017,cluster0-shard-00-01-5pgij.mongodb.net:27017,cluster0-shard-00-02-5pgij.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin",
                EventTypeHeader         = "FourSolidEventName",
                AggregateTypeHeader     = "FourSolidAggregateName"
            };

            var eventDataFactory = new EventDataFactory(eventStoreConfiguration);

            var eventStoreRepository = new EventStoreRepository(eventStoreConfiguration, eventDataFactory);

            var deviceGuid = Guid.NewGuid();
            var device     = Device.CreateDevice(deviceGuid, "AB1234DE", "AB1234DE", DateTime.UtcNow);

            eventStoreRepository.SaveAsync(device, Guid.NewGuid(), d => { }).GetAwaiter().GetResult();

            device = eventStoreRepository.GetByIdAsync <Device>(deviceGuid).GetAwaiter().GetResult();
            device.UpdateSerialNumber("BC2345EF");
            eventStoreRepository.SaveAsync(device, Guid.NewGuid(), d => { }).GetAwaiter().GetResult();

            Console.WriteLine($"Device Id: {device.Id}");
            Console.WriteLine($"Serial Number: {device.GetSerialNumber()}");
            Console.ReadLine();
        }
        public async Task <TAggregate> GetByIdAsync <TAggregate>(string bucketId, Guid id, int version) where TAggregate : class, IAggregate
        {
            var aggregate = EventStoreRepository.ConstructAggregate <TAggregate>();
            await Task.Run(() => this._givenEvents.ForEach(aggregate.ApplyEvent));

            return(aggregate);
        }
Exemplo n.º 9
0
        private static void OrganizationTest(EventStoreRepository repo)
        {
            var organizationId = Guid.NewGuid();

            System.Console.WriteLine("Enter organization name:");
            var orgname = Console.ReadLine();

            var orgCreatec = new OrganizationCreated {
                Name = orgname
            };

            repo.WriteEvents(new AggregateKey(typeof(Organization), organizationId), new[] { orgCreatec });

            string newName = null;

            do
            {
                var history = repo.ReadEvents(new AggregateKey(typeof(Organization), organizationId));

                var organization = new Organization(organizationId, history);
                System.Console.WriteLine("");
                System.Console.WriteLine("Organization " + organization.Name);
                System.Console.WriteLine("Rename: (q to exit)");
                newName = Console.ReadLine();

                if (!string.IsNullOrWhiteSpace(newName.Replace("q", "")))
                {
                    organization.Rename(newName);
                    organization.Save(repo);
                }
            }while (newName != "q");
        }
        public async Task GetByIdAsyncWithoutEventsShouldReturnEmptyList()
        {
            //Arrange
            var optionsBuilder = new DbContextOptionsBuilder <DataBaseContext>();

            optionsBuilder.UseInMemoryDatabase("FakeInMemoryData");
            var moqContext = new DataBaseContext(optionsBuilder.Options);

            moqContext.Database.EnsureCreated();

            var aggregate = (StubAggregate)typeof(StubAggregate)
                            .GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic,
                                            null,
                                            new Type[0],
                                            new ParameterModifier[0])
                            ?.Invoke(new object[0]);

            var moqInvoker = new Mock <IInvoker <StubAggregate> >();

            moqInvoker.Setup(i => i.CreateInstanceOfAggregateRoot <StubAggregate>()).Returns(aggregate);

            var sut         = new EventStoreRepository <StubAggregate>(moqContext, moqInvoker.Object, It.IsAny <IDomainEventRebuilder>());
            var aggregateId = Guid.NewGuid();

            //Act
            var result = await sut.GetByIdAsync <StubAggregate>(aggregateId);

            //Assert
            Assert.Equal(aggregate, result);
        }
Exemplo n.º 11
0
        public async Task <HookResult> AppendAll(List <DomainEventBase> domainEvents)
        {
            var domainEventsFromHooks = new List <DomainEventBase>();
            var enumerator            = domainEvents.GetEnumerator();

            for (
                ; enumerator.MoveNext();
                )
            {
                var domainEvent    = enumerator.Current;
                var domainHooks    = DomainHooks.Where(hook => hook.EventType == domainEvent.GetType());
                var enumeratorHook = domainHooks.GetEnumerator();
                for (
                    ; enumeratorHook.MoveNext();
                    )
                {
                    var domainHook       = enumeratorHook.Current;
                    var validationResult = await domainHook.ExecuteSavely(domainEvent);

                    if (!validationResult.Ok)
                    {
                        return(validationResult);
                    }
                    domainEventsFromHooks.AddRange(validationResult.DomainEvents);
                }
            }
            await EventStoreRepository.AddEvents(domainEvents);

            await EventStoreRepository.AddEvents(domainEventsFromHooks);

            return(HookResult.OkResult());
        }
Exemplo n.º 12
0
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            var eventStore = getInitializedEventStore(new DispatchCommits(container.Resolve<IServiceBus>()));
            container.Register(Component.For<IStoreEvents>().Instance(eventStore).LifeStyle.Singleton);

            var repository = new EventStoreRepository(eventStore, new AggregateFactory(), new ConflictDetector());
            container.Register(Component.For<IRepository>().Instance(repository).LifeStyle.Singleton);
        }
Exemplo n.º 13
0
 public EventStoreRepositoryBuilder(EventStoreRepository eventStoreRepository)
 {
     _eventStoreRepository   = eventStoreRepository;
     _nameSpaceBuilderUtil   = new NameSpaceBuilderUtil();
     _propertyBuilderUtil    = new PropertyBuilderUtil();
     _constructorBuilderUtil = new ConstructorBuilderUtil();
     _classBuilderUtil       = new ClassBuilderUtil();
 }
Exemplo n.º 14
0
        public async Task Create()
        {
            EventStoreRepository sut = await GetSut();

            var foo = new SampleDomainObject("a04s4ac4-16eb-4b6b-aeea-12b2e034a408");

            foo.Add();
            await sut.SaveAsync(foo);
        }
Exemplo n.º 15
0
        /// <summary>
        ///
        /// </summary>
        protected override void LazyInit(ref IStoreEvents storeEventsInstance, object lockObject)
        {
            base.LazyInit(ref storeEventsInstance, lockObject);

            if (_repository == null)
            {
                _repository = new EventStoreRepository(storeEventsInstance, new AggregateFactory(), new ConflictDetector());
            }
        }
Exemplo n.º 16
0
        public static void ClassInitialise(TestContext context)
        {
            bus = new InProcessBus(DispatchStrategy.Asynchronous);

            store = Wireup.Init()
                    .UsingInMemoryPersistence()
                    .Build();
            repository = new EventStoreRepository(store, new AggregateFactory(), new ConflictDetector());
        }
Exemplo n.º 17
0
        public async Task ItCallsTheConnections()
        {
            var con = A.Fake <IEventStoreConnection>();

            EventStoreRepository sut = GetSut("UnitTest", con);

            var domainObj = new SampleDomainObject("1");
            await sut.SaveAsync(domainObj);
        }
Exemplo n.º 18
0
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            var eventStore = getInitializedEventStore(new DispatchCommits(container.Resolve <IServiceBus>()));

            container.Register(Component.For <IStoreEvents>().Instance(eventStore).LifeStyle.Singleton);

            var repository = new EventStoreRepository(eventStore, new AggregateFactory(), new ConflictDetector());

            container.Register(Component.For <IRepository>().Instance(repository).LifeStyle.Singleton);
        }
Exemplo n.º 19
0
        public static void Init()
        {
            var storeEvents = WireupEventStore();
            var aggregateFactory = new AggregateFactory();
            var conflictDetector = new ConflictDetector();
            var eventRepository = new EventStoreRepository(storeEvents, aggregateFactory, conflictDetector);

            _commandHandlerService = new CommandHandlerService();
            _commandHandlerService.InitHandlers(eventRepository);
        }
Exemplo n.º 20
0
        public async Task Update()
        {
            var id = "a04s4ac4-16eb-4b6b-aeea-12b2e034a408";
            EventStoreRepository sut = await GetSut();

            SampleDomainObject result = await sut.Get <SampleDomainObject>(id);

            result.Add();

            await sut.SaveAsync(result);
        }
Exemplo n.º 21
0
        /// <summary>Gets the by identifier.</summary>
        /// <param name="identifier">The identifier.</param>
        /// <returns>A <see cref="SystemAccount" />.</returns>
        public SystemAccount GetByIdentifier(string identifier)
        {
            var eventStore = _eventStoreFactory.Build <SystemAccount> ();
            var commits    = eventStore.Advanced.GetFrom(DateTime.MinValue);
            var systemAccountCreatedEvent = commits.SelectMany(c => c.Events)
                                            .FirstOrDefault(e => e.Body is SystemAccountCreatedEvent && (e.Body as SystemAccountCreatedEvent).Identifier == identifier);

            return(systemAccountCreatedEvent == null ? null : EventStoreRepository.GetByKey <SystemAccount> ((systemAccountCreatedEvent.Body as SystemAccountCreatedEvent).Key));

            //TODO: See if there is a way to do this without hitting the event store twice.
        }
Exemplo n.º 22
0
        void WithEventstore(Action <IAggregateEventStore> work)
        {
            var switchboard = new Nuclear.Lazy.Switchboard();
            IEventStoreConnection connection = EventStoreConnection.Create(new IPEndPoint(IPAddress.Loopback, 1113));

            connection.ConnectAsync().Wait();
            IAggregateEventStore eventstore = new EventStoreRepository(connection, switchboard);

            work(eventstore);
            connection.Close();
        }
Exemplo n.º 23
0
        public async Task BuildRepositories(Protocol chosenProtocol = Protocol.Tcp)
        {
            protocol = chosenProtocol;

            EventReader = await ConfigureReader();

            EventWriter = await ConfigureWriter();

            repository         = new EventStoreRepository <string, IHoldHigherOrder>(validator, configuration, EventReader, EventWriter, DateTimeProvider);
            readOnlyRepository = new EventStoreReadOnlyRepository <string, IHoldHigherOrder>(configuration, EventReader);
        }
Exemplo n.º 24
0
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            //Bus
            var bus = new InProcessBus(container);
            container.Register(Component.For<IBus>().Instance(bus));

            var eventStore = GetInitializedEventStore(bus);
            var repository = new EventStoreRepository(eventStore, new AggregateFactory(), new ConflictDetector());

            container.Register(Component.For<IStoreEvents>().Instance(eventStore));
            container.Register(Component.For<IRepository>().Instance(repository));
        }
Exemplo n.º 25
0
        private void ConfigureHandlers()
        {
            var bus = new RabbitMqBus(RabbitHutch.CreateBus("host=localhost"));
            ServiceLocator.Bus = bus;

            //Should get this from a config setting instead of hardcoding it.
            var eventStoreConnection = EventStoreConnection.Create(new IPEndPoint(IPAddress.Loopback, 12900));
            eventStoreConnection.ConnectAsync().Wait();
            var repository = new EventStoreRepository(eventStoreConnection, bus);

            ServiceLocator.ProductCommands = new ProductCommandHandlers(repository);
        }
        public async Task GetByIdAsyncWithBadAggregateIdShouldRaiseBadAggregateIdException()
        {
            //Arrange
            var moqDb       = new Mock <DataBaseContext>();
            var sut         = new EventStoreRepository <StubAggregate>(moqDb.Object, It.IsAny <IInvoker <StubAggregate> >(), It.IsAny <IDomainEventRebuilder>());
            var aggregateId = Guid.Empty;

            //Act
            //Assert
            await Assert.ThrowsAsync <BadAggregateIdException>(() =>
                                                               sut.GetByIdAsync <StubAggregate>(aggregateId));
        }
Exemplo n.º 27
0
        public EventStoreRepositoryTests()
        {
            _testDbContext = new YSecTestEventStoreContext();

            _events = GenerateEvents();

            _testDbContext.Events.AddRange(_events);

            _testDbContext.SaveChanges();

            _eventStoreRepository = new EventStoreRepository(_testDbContext);
        }
Exemplo n.º 28
0
        public void Setup()
        {
            var unitOfWorkMock         = new Mock <IUnitOfWork>();
            var unitOfWorkProviderMock = new Mock <IUnitOfWorkProvider>();

            unitOfWorkProviderMock.Setup(u => u.GetCurrentUnitOfWork()).Returns(unitOfWorkMock.Object);

            _eventStoreRepository = new EventStoreRepository(new InMemoryEventStoreFactory(),
                                                             new AggregateFactory(),
                                                             new Mock <IDetectConflicts>().Object,
                                                             unitOfWorkProviderMock.Object);
        }
        public static void ClassInitialise(TestContext context)
        {
            bus = new InProcessBus(DispatchStrategy.Synchronous);

            client = new SomeAwesomeUi(bus);

            store = Wireup.Init().UsingInMemoryPersistence().Build();
            var repository = new EventStoreRepository(store, new AggregateFactory(), new ConflictDetector());
            var handler    = new CreateAccountCommandHandler(repository);

            bus.Subscribe(handler);
            accountId = client.CreateNewAccount();
        }
        public void Reprioritized_Project_Can_Be_Saved_In_Event_Store()
        {
            var project = new Project(new Title("my project"), new ProjectDeadline(DateTime.UtcNow));

            project.Reprioritize(ProjectPriority.Medium);
            var eventStoreRepository = new EventStoreRepository <Project>(EventBus, InMemoryEventStoreConnectionBuilder);

            eventStoreRepository.Save(project);

            Project projectFromEventStore = eventStoreRepository.GetById(project.Id);

            Assert.That(projectFromEventStore.Version, Is.EqualTo(2));
        }
Exemplo n.º 31
0
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            //Bus
            var bus = new InProcessBus(container);

            container.Register(Component.For <IBus>().Instance(bus));

            var eventStore = GetInitializedEventStore(bus);
            var repository = new EventStoreRepository(eventStore, new AggregateFactory(), new ConflictDetector());

            container.Register(Component.For <IStoreEvents>().Instance(eventStore));
            container.Register(Component.For <IRepository>().Instance(repository));
        }
Exemplo n.º 32
0
        public void ShouldThrowForEventStoreRepository()
        {
            // arrange
            var identityMap = new MemoryIdentityMap();
            var repository  = new EventStoreRepository(identityMap, new MemoryEventStore(), new MemorySnapshotStore());
            var naturalKey  = "key";

            // act
            identityMap.GetOrAdd(typeof(Subject), typeof(string), naturalKey);
            Action action = () => repository.Load <Subject>(naturalKey);

            // assert
            action.ShouldThrow <AggregateRootNotFoundException>();
        }
Exemplo n.º 33
0
        public static void RegisterEventStore()
        {
            //use a global singleton instead of IoC for this workshop
            var bus = new InProcessBus();
            Globals.Bus = bus;

            var eventStore = GetInitializedEventStore(bus);
            var repository = new EventStoreRepository(eventStore, new AggregateFactory(), new ConflictDetector());

            Globals.EventStore = eventStore;
            Globals.Repository = repository;

            Globals.ApplicationService = new HostDinnerApplicationService(Globals.Repository);
        }
Exemplo n.º 34
0
        private void ConfigureHandlers()
        {
            var bus = new RabbitMqBus(RabbitHutch.CreateBus("host=localhost"));

            ServiceLocator.Bus = bus;

            //Should get this from a config setting instead of hardcoding it.
            var eventStoreConnection = EventStoreConnection.Create(new IPEndPoint(IPAddress.Loopback, 12900));

            eventStoreConnection.ConnectAsync().Wait();
            var repository = new EventStoreRepository(eventStoreConnection, bus);

            ServiceLocator.ProductCommands = new ProductCommandHandlers(repository);
        }
Exemplo n.º 35
0
        private static async Task <Dispatcher> SetupDispatcher()
        {
            var eventStoreConnection = EventStoreConnection.Create(
                ConnectionSettings.Default,
                new IPEndPoint(IPAddress.Loopback, 1113));

            await eventStoreConnection.ConnectAsync();

            var repository = new EventStoreRepository(eventStoreConnection);

            var commandHandlerMap = new CommandHandlerMap(new Handlers(repository));

            return(new Dispatcher(commandHandlerMap));
        }
Exemplo n.º 36
0
        public static IDomainContext GetDomainContext()
        {
            KnownTypes.RegisterEvents(Assembly.GetExecutingAssembly());

            var manifest = new SqlAggregateManifestRepository(EventSourcedDB.Main);

            var eventStore = new EventStoreRepository(EventSourcedDB.Main);

            var context = new TestDomainContext(EventSourcedDB.Main, manifest, eventStore);
            context.EventBus.Subscribe((x) => Console.WriteLine("domain bus event {0}", x));

            // registrations
            context.RegisterBuilder<EventSourcedRoot>((c) =>
                 new TransactionReadModelBuilder(new SqlRepository<TransactionDataContract>(EventSourcedDB.Main)));

            return context;
        }
Exemplo n.º 37
0
        public static void RegisterEventStore()
        {
            //use a global singleton instead of IoC for this workshop
            var bus = new InProcessBus();
            Globals.Bus = bus;

            var eventStore = GetInitializedEventStore(bus);
            var repository = new EventStoreRepository(eventStore, new AggregateFactory(), new ConflictDetector());

            Globals.EventStore = eventStore;
            Globals.Repository = repository;

            Globals.ApplicationService = new HostDinnerApplicationService(Globals.Repository);

            var documentStore = new DocumentStore {Url = "http://localhost:8080/", DefaultDatabase = "NerdDinner"};
            documentStore.Initialize();
            Globals.RavenDocumentStore = documentStore;

            SetupDomainEventHandlers(bus);
        }
Exemplo n.º 38
0
        private void ConfigureHandlers()
        {
            var b = RabbitHutch.CreateBus("host=localhost");

            var messageBusEndPoint = "barista";
            var topicFilter = "Cashier.Common.Events";

            var bus = new RabbitMqBus(b);
            ServiceLocator.Bus = bus;

            //Should get this from a config setting instead of hardcoding it.
            var eventStoreConnection = EventStoreConnection.Create(new IPEndPoint(IPAddress.Loopback, 12900));
            eventStoreConnection.ConnectAsync().Wait();
            var repository = new EventStoreRepository(eventStoreConnection, bus);

            ServiceLocator.OrderCommands = new BaristaOrderCommandHandlers(repository);

            var cashierEventHandler = new CashierOrderEventHandler(repository);
            ServiceLocator.CahierEventHandler = cashierEventHandler;

            var eventMappings = new EventHandlerDiscovery()
                .Scan(cashierEventHandler)
                .Handlers;

            b.Subscribe<PublishedMessage>(messageBusEndPoint,
            m =>
            {
                Aggregate handler;
                var messageType = Type.GetType(m.MessageTypeName);
                var handlerFound = eventMappings.TryGetValue(messageType, out handler);
                if (handlerFound)
                {
                    var @event = JsonConvert.DeserializeObject(m.SerialisedMessage, messageType);
                    handler.AsDynamic().ApplyEvent(@event, ((Event)@event).Version);
                }
            },
            q => q.WithTopic(topicFilter));
        }
        public void Setup()
        {
            this.eventstore = Wireup.Init()
                .UsingInMemoryPersistence()
                .UsingSynchronousDispatchScheduler()
                .DispatchTo(new DelegateMessageDispatcher(c =>
                                {
                                    c.Events.ForEach(dispatchedEvents.Add);
                                    c.Events.Select(m=>m.Body).ToList().ForEach(bus.Publish);
                                }))
                .Build();

            var aggregateRepository = new EventStoreRepository(
                eventstore
                , new AggregateFactory()
                ,new ConflictDetector());

            var updateStorage = new InMemoryDbUpdateStorage();
            this.readStorage = updateStorage;

            this.bus = ServiceBusFactory.New(sbc =>
                {
                    sbc.ReceiveFrom("loopback://localhost/test");
                    sbc.Subscribe(x => x.Consumer(() => new ManagerCommandHandler(aggregateRepository)));
                    sbc.Subscribe(x => x.Consumer(() => new ManagerInfoDenormalizer(updateStorage)));
                });

            var createManagerCommand = new CreateManager(managerId, "Max", "Cole");
            bus.Publish(createManagerCommand);

            TaskManager taskManager = new TaskManager(TimeSpan.FromMilliseconds(500));
            taskManager.
                When(() => this.readStorage.Items<ManagerInfo>().Any()).
                Then(()=>this.sync.Set());
            this.sync.WaitOne(TimeSpan.FromSeconds(5));
        }
Exemplo n.º 40
0
        private void ConfigureHandlers()
        {
            var b = RabbitHutch.CreateBus("host=localhost");
            var bus = new RabbitMqBus(b);
            ServiceLocator.Bus = bus;

            var messageBusEndPoint = "cashier_service";
            var topicFilter = "Admin.Common.Events";

            var eventStorePort = 12900;

            var eventStoreConnection = EventStoreConnection.Create(new IPEndPoint(IPAddress.Loopback, eventStorePort));
            eventStoreConnection.ConnectAsync().Wait();
            var repository = new EventStoreRepository(eventStoreConnection, bus);

            ServiceLocator.OrderCommands = new OrderCommandHandlers(repository);
            ServiceLocator.ProductView = new ProductView();

            var eventMappings = new EventHandlerDiscovery()
                .Scan(new AdminEventsHandler())
                .Handlers;

            b.Subscribe<PublishedMessage>(messageBusEndPoint,
            m =>
            {
                Aggregate handler;
                var messageType = Type.GetType(m.MessageTypeName);
                var handlerFound = eventMappings.TryGetValue(messageType, out handler);
                if (handlerFound)
                {
                    var @event = JsonConvert.DeserializeObject(m.SerialisedMessage, messageType);
                    handler.AsDynamic().ApplyEvent(@event, ((Event)@event).Version);
                }
            },
            q => q.WithTopic(topicFilter));
        }
Exemplo n.º 41
0
 public DiscussionCommandHandler(EventStoreRepository<Discussion> repository)
 {
     _repository = repository;
 }
Exemplo n.º 42
0
 public LinkCommandHandler(EventStoreRepository<Link> repository)
 {
     _repository = repository;
 }
Exemplo n.º 43
0
 public UserCommandHandler(EventStoreRepository<User> repository)
 {
     _repository = repository;
 }
 public void Initialize()
 {
     _eventStoreRepository = new EventStoreRepository<Guid>();
 }
Exemplo n.º 45
0
        public void Initialize()
        {
            InitializeViewCreators();

            var repository = new EventStoreRepository(
                Wireup.Init().
                    UsingSqlPersistence("EntileEventStore").InitializeStorageEngine().
                    UsingJsonSerialization().UsingAsynchronousDispatchScheduler(
                        new DelegateMessageDispatcher(c =>
                                                         {
                                                             foreach (var e in c.Events)
                                                             {
                                                                 _viewCreatorsDispatcher.Dispatch(e.Body as IMessage);
                                                             }
                                                         })).
                    Build(),
                new AggregateFactory(), new ConflictDetector());

            InitializeClientCommands(repository);
        }