private static IEventBus InitializeEventBus() { var bus = new InProcessEventBus(); bus.RegisterAllHandlersInAssembly(typeof(NoteItemDenormalizer).Assembly); return bus; }
static void Main(string[] args) { Console.WindowHeight = 30; Console.WindowWidth = 150; var bus = new InProcessEventBus(true); var eventStore = Program.GetBrowsableEventStore(); var buffer = new InMemoryBufferedBrowsableElementStore(eventStore, 20 /*magic number found in ThresholdFetchPolicy*/); bus.RegisterAllHandlersInAssembly(typeof(MyNotes.Denormalizers.NoteDenormalizer).Assembly); BootStrapper.BootUp(buffer); var pipeline = Pipeline.Create("Default", new EventBusProcessor(bus), buffer); pipeline.Start(); var commandServiceHost = new ServiceHost(typeof(CommandWebService)); commandServiceHost.Open(); Console.ReadLine(); commandServiceHost.Close(); pipeline.Stop(); }
public void Durable_consequenters_can_be_simulated_for_unit_testing_and_receive_messages() { var consequenter1WasCalled = false; var consequenter2WasCalled = false; var uselessSettings = new ServiceBusSettings(); using (ServiceBusDurabilityExtensions.Simulate()) { var consequenter1 = Consequenter.Create <Order.Cancelled>( e => { consequenter1WasCalled = true; }); var consequenter2 = Consequenter.Create <Order.CreditCardCharged>( e => { consequenter2WasCalled = true; }); var bus = new InProcessEventBus(); bus.Subscribe( consequenter1.UseServiceBusForDurability(uselessSettings), consequenter2.UseServiceBusForDurability(uselessSettings)); bus.PublishAsync(new Order.Cancelled()).Wait(); consequenter1WasCalled.Should().BeTrue(); consequenter2WasCalled.Should().BeFalse(); } }
public void When_multiple_consequenter_handlers_are_chained_then_the_last_added_is_called_first() { // arrange var bus = new InProcessEventBus(); var handlerCalls = new List <string>(); // act var handler = new TestConsequenter() .WrapAll((e, next) => { handlerCalls.Add("c"); next(e); }) .WrapAll((e, next) => { handlerCalls.Add("b"); next(e); }) .WrapAll((e, next) => { handlerCalls.Add("a"); next(e); }); bus.Subscribe(handler); bus.PublishAsync(new Order.Created()).Wait(); // assert handlerCalls.Should().BeInAscendingOrder(); }
public void Handler_chains_can_be_specified_for_all_event_types_on_a_single_projector() { // arrange var bus = new InProcessEventBus(); var createdWasCalled = false; var cancelledWasCalled = false; var deliveredWasCalled = false; var handledEvents = new List <IEvent>(); // act var handler = new TestProjector( onCreated: e => createdWasCalled = true, onCancelled: e => cancelledWasCalled = true, onDelivered: e => deliveredWasCalled = true) .WrapAll((e, nextHandler) => { handledEvents.Add(e); nextHandler(e); }); bus.Subscribe(handler); bus.PublishAsync(new Order.Created()).Wait(); bus.PublishAsync(new Order.Cancelled()).Wait(); bus.PublishAsync(new Order.Delivered()).Wait(); // assert handledEvents.Count.Should().Be(3); createdWasCalled.Should().BeTrue("created was called"); cancelledWasCalled.Should().BeTrue("cancelled was called"); deliveredWasCalled.Should().BeTrue("delivered was called"); }
public override async Task When_storage_fails_then_no_events_are_published() { var order = new Order(); var bus = new InProcessEventBus(); var eventsPublished = new List <IEvent>(); bus.Events <IEvent>().Subscribe(eventsPublished.Add); Func <EventStoreDbContext> eventStoreDbContext = () => { throw new Exception("oops!"); }; var repository = new SqlEventSourcedRepository <Order>(bus, eventStoreDbContext); order .Apply(new AddItem { ProductName = "Widget", Price = 10m, Quantity = 2 }); try { await repository.Save(order); } catch { } eventsPublished.Should().BeEmpty(); }
public async Task When_a_handler_chain_throws_then_subsequent_events_are_still_published() { // arrange var bus = new InProcessEventBus(); var errors = new List <EventHandlingError>(); bus.Errors.Subscribe(errors.Add); var callCount = 0; // act var handler = new TestConsequenter() .WrapAll((e, next) => { callCount++; if (callCount == 1) { throw new Exception("oops!"); } }); bus.Subscribe(handler); await bus.PublishAsync(new Order.Created()); await bus.PublishAsync(new Order.Created()); // assert callCount.Should().Be(2); }
public void InProcessEventBus_Publishes_Events() { var events = new List <DomainEvent> { new SomethingHappenedEvent(), new SomethingHappenedEvent() }; var handler1 = new Mock <IHandleDomainEvents <SomethingHappenedEvent> >(); var handler2 = new Mock <IHandleDomainEvents <SomethingHappenedEvent> >(); handler1.Setup(h => h.Handle(It.IsAny <SomethingHappenedEvent>())); handler2.Setup(h => h.Handle(It.IsAny <SomethingHappenedEvent>())); var resolver = new Mock <IDependencyResolver>(); resolver.Setup(r => r.ResolveAll(It.IsAny <Type>())).Returns( new List <IHandleDomainEvents <SomethingHappenedEvent> > { handler1.Object, handler2.Object }); var bus = new InProcessEventBus(resolver.Object); bus.PublishEvents(events); handler1.Verify(h => h.Handle(It.IsAny <SomethingHappenedEvent>()), Times.Exactly(2)); handler2.Verify(h => h.Handle(It.IsAny <SomethingHappenedEvent>()), Times.Exactly(2)); }
private static IEventBus InitializeEventBus() { var bus = new InProcessEventBus(); bus.RegisterHandler( new TweetListItemDenormalizer() ); return bus; }
private static IEventBus InitializeEventBus() { var bus = new InProcessEventBus(); bus.RegisterAllHandlersInAssembly(typeof(NoteItemDenormalizer).Assembly); return(bus); }
private static IEventBus InitializeEventBus() { var bus = new InProcessEventBus(); bus.RegisterAllHandlersInAssembly(typeof(BootStrapper).Assembly); return bus; }
private static IEventBus InitializeEventBus(IEventHandler<NewNoteAdded> handler, TextChangedHandler textChangedHandler) { var bus = new InProcessEventBus(); bus.RegisterHandler(handler); bus.RegisterHandler(textChangedHandler); return bus; }
private static IEventBus InitializeEventBus(InMemoryBufferedBrowsableElementStore buffer) { var bus = new InProcessEventBus(); bus.RegisterHandler(new InMemoryBufferedEventHandler(buffer)); return(bus); }
private static IEventBus InitializeEventBus(InMemoryBufferedBrowsableElementStore buffer) { var bus = new InProcessEventBus(); bus.RegisterHandler(new InMemoryBufferedEventHandler(buffer)); return bus; }
private static IEventBus InitializeEventBus() { var bus = new InProcessEventBus(); bus.RegisterHandler(new TweetListItemDenormalizer()); return(bus); }
private static IEventBus BuildEventBus() { var denormalizerAssembly = typeof (ProjectDenormalizer).Assembly; var bus = new InProcessEventBus(); bus.RegisterAllHandlersInAssembly(denormalizerAssembly); return bus; }
private static IEventBus InitializeEventBus(IEventHandler <NewNoteAdded> handler, TextChangedHandler textChangedHandler) { var bus = new InProcessEventBus(); bus.RegisterHandler(handler); bus.RegisterHandler(textChangedHandler); return(bus); }
private static IEventBus BuildEventBus() { var denormalizerAssembly = typeof(ProjectDenormalizer).Assembly; var bus = new InProcessEventBus(); bus.RegisterAllHandlersInAssembly(denormalizerAssembly); return(bus); }
private static IEventBus InitializeEventBus() { var bus = new InProcessEventBus(); bus.RegisterHandler(new VoyageCreatedDenormalizer()); bus.RegisterHandler(new CargoCreatedDenormalizer()); bus.RegisterHandler(new CargoAddedToVoyageUpdateCapacityDenormalizer()); bus.RegisterHandler(new CargoAddedToVoyageUpdateCargoDenormalizer()); return bus; }
public void Configure(Configure config) { Builder = config.Builder; Configurer = config.Configurer; NcqrsEnvironment.Configure(new NsbEnvironmentConfiguration(Builder)); _inProcessEventBus = new InProcessEventBus(false); NcqrsEnvironment.SetDefault <IEventBus>(_inProcessEventBus); _commandService = new NsbCommandService(); config.Configurer.RegisterSingleton(typeof(ICommandService), _commandService); }
public void events_emitted_should_be_collected() { var domain = Substitute.For<Domain>(null, null, null); var inProcessBus = new InProcessEventBus(); var expected = new DogRegistered("test", "wibble"); inProcessBus.Emit(new RaisedEvent(expected, DateTimeOffset.UtcNow)); inProcessBus.StartCollectingEvents(domain); inProcessBus.StopCollecting(() => domain.Received().Consume(Arg.Is<RaisedEvent>(_ => _.Event == expected))); }
private static IDisposable SubscribeToReceiveMessages <THandler>( IEventHandlerBinder binder, THandler handler, ServiceBusSettings settings, Configuration configuration, Dictionary <Type, QueueClient> queues) where THandler : class { Type eventType = ((dynamic)binder).EventType; var queueName = string.Format("{0}_on_{1}.{2}", EventHandler.Name(handler), eventType.AggregateTypeForEventType().Name, eventType.EventName()); var bus = new InProcessEventBus(errorSubject: (ISubject <EventHandlingError>)configuration.EventBus.Errors); var eventBusSubscription = binder.SubscribeToBus(handler, bus); var receive = SimulatedReceive; if (receive != null) { var receiveSubscription = receive.Subscribe(e => bus.PublishAsync(e).Subscribe(_ => { }, ex => bus.PublishErrorAsync(new EventHandlingError(ex, @event: e)))); return(new CompositeDisposable(eventBusSubscription, receiveSubscription)); } var queueClient = settings.CreateQueueClient( queueName, settings.ConfigureQueue); // starting listening on the queue for incoming events queueClient.OnMessage(msg => { var storedEvent = msg.GetBody <string>() .FromJsonTo <StoredEvent>(); var @event = Serializer.DeserializeEvent( aggregateName: storedEvent.AggregateName, eventName: storedEvent.EventName, body: storedEvent.Body, aggregateId: storedEvent.AggregateId, sequenceNumber: storedEvent.SequenceNumber, timestamp: storedEvent.Timestamp); bus.PublishAsync(@event).Subscribe( _ => msg.Complete(), ex => bus.PublishErrorAsync(new EventHandlingError(ex, @event: @event))); }); queues[((dynamic)binder).EventType] = queueClient; return(new CompositeDisposable(eventBusSubscription, Disposable.Create(queueClient.Close))); }
public void When_a_catch_all_handler_is_register_it_should_be_called_for_all_events() { var catchAllEventHandler = MockRepository.GenerateMock<IEventHandler<object>>(); var bus = new InProcessEventBus(); bus.RegisterHandler(catchAllEventHandler); bus.Publish(CreateADomainEvent()); bus.Publish(CreateAEvent()); catchAllEventHandler.AssertWasCalled(h => h.Handle(null), options => options.IgnoreArguments().Repeat.Twice()); }
private static void RegisterHandler(object handler, Type eventDataType, InProcessEventBus target) { var registerHandlerMethod = target.GetType().GetMethods().Single ( m => m.Name == "RegisterHandler" && m.IsGenericMethod && m.GetParameters().Count() == 1 ); var targetMethod = registerHandlerMethod.MakeGenericMethod(new[] { eventDataType }); targetMethod.Invoke(target, new object[] { handler }); _log.InfoFormat("Registered {0} as event handler for event {1}.", handler.GetType().FullName, eventDataType.FullName); }
public void When_a_catch_all_handler_is_register_it_should_be_called_for_all_events() { var catchAllEventHandler = MockRepository.GenerateMock <IEventHandler <object> >(); var bus = new InProcessEventBus(); bus.RegisterHandler(catchAllEventHandler); bus.Publish(CreateADomainEvent()); bus.Publish(CreateAEvent()); catchAllEventHandler.AssertWasCalled(h => h.Handle(null), options => options.IgnoreArguments().Repeat.Twice()); }
public async Task If_Subscribe_is_called_more_than_once_for_a_given_handler_it_is_not_subscribed_again() { var callCount = 0; var handler = Projector.Create <Order.ItemAdded>(e => { callCount++; }); var bus = new InProcessEventBus(); bus.Subscribe(handler); bus.Subscribe(handler); await bus.PublishAsync(new Order.ItemAdded()); callCount.Should().Be(1); }
private static IEventBus InitializeEventBus() { var bus = new InProcessEventBus(); //bus.RegisterHandler(new SqlTweetIndexItemDenormalizer()); bus.RegisterHandler(new FileTweetIndexItemDenormalizer()); bus.RegisterHandler(new FileTweetIndexItemDeleteDenormalizer()); bus.RegisterHandler(new ChannelIndexItemDenormalizer()); bus.RegisterHandler(new UserIndexDenormalizer()); bus.RegisterHandler(new UserIndexDeleteDenormalizer()); bus.RegisterHandler(new UserIndexPropertySetDenormalizer()); bus.RegisterHandler(new UserIndexPasswordSetDenormalizer()); return bus; }
private static IEventBus InitializeEventBus() { var bus = new InProcessEventBus(); // 2 opties: registreer denormalizers stuk voor stuk of registreer de gehele assembly //bus.RegisterHandler(new VoyageCreatedDenormalizer()); //bus.RegisterHandler(new CargoCreatedDenormalizer()); //bus.RegisterHandler(new CargoAddedToVoyageUpdateCapacityDenormalizer()); //bus.RegisterHandler(new CargoAddedToVoyageUpdateCargoDenormalizer()); bus.RegisterAllHandlersInAssembly(Assembly.Load("ReadModel")); return bus; }
private static IEventBus InitializeEventBus(IKernel kernel) { var bus = new InProcessEventBus(); bus.RegisterHandler<MeetingScheduledEvent> (kernel.Get<MeetingDenormalizer>()); bus.RegisterHandler<MeetingScheduledEvent> (kernel.Get<StatDenormalizer>()); bus.RegisterHandler<CommentAddedEvent> (kernel.Get<MeetingDenormalizer>()); bus.RegisterHandler<CommentAddedEvent> (kernel.Get<StatDenormalizer>()); return bus; }
public async Task When_one_command_triggers_another_command_via_a_consequenter_then_the_second_command_acquires_the_first_commands_clock() { // arrange var orderId = Any.Guid(); var customerId = Any.Guid(); var bus = new InProcessEventBus(); var orderRepository = new InMemoryEventSourcedRepository <Order>(bus: bus); await orderRepository.Save(new Order(new CreateOrder(Any.FullName()) { AggregateId = orderId, CustomerId = customerId }).Apply(new AddItem { ProductName = Any.Word(), Quantity = 1, Price = Any.Decimal(.01m, 10m) })); var customerRepository = new InMemoryEventSourcedRepository <CustomerAccount>(); await customerRepository.Save(new CustomerAccount(customerId).Apply(new ChangeEmailAddress(Any.Email()))); #pragma warning disable 618 bus.Subscribe(Consequenter.Create <Order.Shipped>(e => #pragma warning restore 618 { var order = orderRepository.GetLatest(e.AggregateId).Result; var customer = customerRepository.GetLatest(order.CustomerId).Result; customer.Apply(new SendOrderConfirmationEmail(order.OrderNumber)); customerRepository.Save(customer).Wait(); })); var shipDate = DateTimeOffset.Parse("2014-05-15 01:01:01"); var ship = new Ship(); // act using (CommandContext.Establish(ship, Clock.Create(() => shipDate))) { var order = await orderRepository.GetLatest(orderId); order.Apply(ship); await orderRepository.Save(order); } // assert var last = (await customerRepository.GetLatest(customerId)).Events().Last(); last.Should() .BeOfType <CustomerAccount.OrderShipConfirmationEmailSent>(); last.Timestamp.Should().Be(shipDate); }
/// <summary> /// Initializes a new instance of the <see cref="ReadModelCatchup{TDbContext}" /> class. /// </summary> /// <param name="readModelDbContext">A delegate to create read model database contexts on demand.</param> /// <param name="eventStoreDbContext">A delegate to create event store database contexts on demand.</param> /// <param name="startAtEventId">The event id that the catchup should start from.</param> /// <param name="batchSize">The number of events queried from the event store at each iteration.</param> /// <param name="filter">An optional filter expression to constrain the query that the catchup uses over the event store.</param> /// <param name="projectors">The projectors to be updated as new events are added to the event store.</param> /// <exception cref="System.ArgumentNullException"> /// </exception> /// <exception cref="System.ArgumentException">You must specify at least one projector.</exception> public ReadModelCatchup( Func <DbContext> readModelDbContext, Func <EventStoreDbContext> eventStoreDbContext, long startAtEventId = 0, int batchSize = 10000, Expression <Func <StorableEvent, bool> > filter = null, params object[] projectors) { if (readModelDbContext == null) { throw new ArgumentNullException(nameof(readModelDbContext)); } if (eventStoreDbContext == null) { throw new ArgumentNullException(nameof(eventStoreDbContext)); } if (!projectors.OrEmpty().Any()) { throw new ArgumentException("You must specify at least one projector."); } if (batchSize < 1) { throw new ArgumentException($"Argument {nameof(batchSize)} must be at least 1."); } createReadModelDbContext = readModelDbContext; createEventStoreDbContext = eventStoreDbContext; this.startAtEventId = startAtEventId; this.filter = filter; this.projectors = new List <object>(projectors); this.batchSize = batchSize; EnsureProjectorNamesAreDistinct(); cancellationDisposable = new CancellationDisposable(); disposables = new CompositeDisposable { cancellationDisposable, Disposable.Create(() => progress.OnCompleted()) }; bus = new InProcessEventBus(new Subject <IEvent>()); disposables.Add(bus.ReportErrorsToDatabase(() => createReadModelDbContext())); disposables.Add(bus); Sensors.ReadModelDbContexts.GetOrAdd(typeof(TDbContext).Name, createReadModelDbContext); }
public void Configure(Configure config) { Builder = config.Builder; Configurer = config.Configurer; NcqrsEnvironment.Configure(new NsbEnvironmentConfiguration(Builder)); var compositeBus = new CompositeEventBus(); _inProcessEventBus = new InProcessEventBus(false); compositeBus.AddBus(new NsbEventBus()); compositeBus.AddBus(_inProcessEventBus); _sendingEventHandler = new MessageSendingEventHandler(); _inProcessEventBus.RegisterHandler(_sendingEventHandler); NcqrsEnvironment.SetDefault(compositeBus); _messageService = new MessageService(); config.Configurer.RegisterSingleton(typeof(IMessageService), _messageService); }
public void Registering_handler_via_generic_overload_should_also_add_the_handler() { var aDomainEventHandler = MockRepository.GenerateMock<IEventHandler<ADomainEvent>>(); var bus = new InProcessEventBus(); bus.RegisterHandler(aDomainEventHandler); var events = new IPublishableEvent[] { CreateAEvent(), CreateADomainEvent(), CreateADomainEvent(), CreateAEvent(), CreateADomainEvent(), CreateAEvent(), CreateAEvent(), CreateADomainEvent(), CreateADomainEvent(), CreateAEvent(), CreateADomainEvent(), CreateAEvent() }; bus.Publish(events); aDomainEventHandler.AssertWasCalled(h => h.Handle(null), options => options.IgnoreArguments().Repeat.Times(6)); }
public void When_multiple_messages_are_published_at_once_they_all_should_be_published() { var catchAllEventHandler = MockRepository.GenerateMock<IEventHandler<object>>(); var bus = new InProcessEventBus(); bus.RegisterHandler(catchAllEventHandler); var events = new[] { CreateAEvent(), CreateAEvent(), CreateAEvent(), CreateAEvent(), CreateAEvent(), CreateAEvent(), CreateAEvent(), CreateAEvent(), CreateAEvent(), CreateAEvent(), CreateAEvent(), CreateAEvent() }; bus.Publish(events); catchAllEventHandler.AssertWasCalled(h => h.Handle(null), options => options.IgnoreArguments().Repeat.Times(events.Length)); }
public void PublishAndSubscribeEventTest() { InProcessEventBus bus = new InProcessEventBus(); TestEvent testEvent = new TestEvent("some value"); TestEvent receivedEvent = null; bus.Subscribe(new Subscriber(eventEnvelope => receivedEvent = eventEnvelope.GetContent <TestEvent>())); bus.Publish(testEvent); // sleep because the bus publishes events on another thread Thread.Sleep(10); receivedEvent.Should().NotBeNull(); receivedEvent.ShouldBeEquivalentTo(testEvent); }
public void When_multiple_messages_are_published_and_a_specific_handler_is_register_oply_the_matching_events_should_be_received_at_the_handler() { var aDomainEventHandler = MockRepository.GenerateMock <IEventHandler <ADomainEvent> >(); var bus = new InProcessEventBus(); bus.RegisterHandler(aDomainEventHandler); var events = new IPublishableEvent[] { CreateAEvent(), CreateADomainEvent(), CreateADomainEvent(), CreateAEvent(), CreateADomainEvent(), CreateAEvent(), CreateAEvent(), CreateADomainEvent(), CreateADomainEvent(), CreateAEvent(), CreateADomainEvent(), CreateAEvent() }; bus.Publish(events); aDomainEventHandler.AssertWasCalled(h => h.Handle(null), options => options.IgnoreArguments().Repeat.Times(6)); }
public void Registering_handler_via_generic_overload_should_also_add_the_handler() { var aDomainEventHandler = MockRepository.GenerateMock <IEventHandler <ADomainEvent> >(); var bus = new InProcessEventBus(); bus.RegisterHandler(aDomainEventHandler); var events = new IPublishableEvent[] { CreateAEvent(), CreateADomainEvent(), CreateADomainEvent(), CreateAEvent(), CreateADomainEvent(), CreateAEvent(), CreateAEvent(), CreateADomainEvent(), CreateADomainEvent(), CreateAEvent(), CreateADomainEvent(), CreateAEvent() }; bus.Publish(events); aDomainEventHandler.AssertWasCalled(h => h.Handle(null), options => options.IgnoreArguments().Repeat.Times(6)); }
public void When_multiple_messages_are_published_at_once_they_all_should_be_published() { var catchAllEventHandler = MockRepository.GenerateMock <IEventHandler <object> >(); var bus = new InProcessEventBus(); bus.RegisterHandler(catchAllEventHandler); var events = new[] { CreateAEvent(), CreateAEvent(), CreateAEvent(), CreateAEvent(), CreateAEvent(), CreateAEvent(), CreateAEvent(), CreateAEvent(), CreateAEvent(), CreateAEvent(), CreateAEvent(), CreateAEvent() }; bus.Publish(events); catchAllEventHandler.AssertWasCalled(h => h.Handle(null), options => options.IgnoreArguments().Repeat.Times(events.Length)); }
public void When_a_handler_is_registered_for_a_specific_type_it_should_not_receive_other_events() { var aDomainEventEventHandler = MockRepository.GenerateMock<IEventHandler<ADomainEvent>>(); var bus = new InProcessEventBus(); bus.RegisterHandler(aDomainEventEventHandler); bus.Publish(CreateADomainEvent()); bus.Publish(CreateAEvent()); bus.Publish(CreateAEvent()); bus.Publish(CreateADomainEvent()); bus.Publish(CreateAEvent()); bus.Publish(CreateAEvent()); bus.Publish(CreateAEvent()); aDomainEventEventHandler.AssertWasCalled(h => h.Handle(null), options => options.IgnoreArguments().Repeat.Twice()); }
public void When_a_consequenter_that_has_been_chained_throws_then_the_EventHandlingError_Handler_references_the_inner_handler() { // arrange var bus = new InProcessEventBus(); var errors = new List <EventHandlingError>(); bus.Errors.Subscribe(errors.Add); // act var handler = new TestConsequenter(onCreated: e => { throw new Exception("oops!"); }); bus.Subscribe(handler); bus.PublishAsync(new Order.Created()).Wait(); // assert errors.Should().ContainSingle(e => e.Handler is TestConsequenter); }
public void When_a_handler_is_registered_for_a_specific_type_it_should_not_receive_other_events() { var aDomainEventEventHandler = MockRepository.GenerateMock <IEventHandler <ADomainEvent> >(); var bus = new InProcessEventBus(); bus.RegisterHandler(aDomainEventEventHandler); bus.Publish(CreateADomainEvent()); bus.Publish(CreateAEvent()); bus.Publish(CreateAEvent()); bus.Publish(CreateADomainEvent()); bus.Publish(CreateAEvent()); bus.Publish(CreateAEvent()); bus.Publish(CreateAEvent()); aDomainEventEventHandler.AssertWasCalled(h => h.Handle(null), options => options.IgnoreArguments().Repeat.Twice()); }
static void Main(string[] args) { var bus = new InProcessEventBus(true); bus.RegisterAllHandlersInAssembly(typeof(Program).Assembly); var browsableEventStore = new MsSqlServerEventStoreElementStore(Settings.Default.EventStoreConnectionString); var buffer = new InMemoryBufferedBrowsableElementStore(browsableEventStore, 20 /*magic number faund in ThresholedFetchPolicy*/); var pipeline = Pipeline.Create("Default", new EventBusProcessor(bus), buffer); BootStrapper.BootUp(buffer); var commandServiceHost = new ServiceHost(typeof(CommandWebService)); commandServiceHost.Open(); pipeline.Start(); Console.ReadLine(); pipeline.Stop(); commandServiceHost.Close(); }
private static IEventBus InitializeEventBus() { var bus = new InProcessEventBus(); //bus.RegisterHandler(new SqlTweetIndexItemDenormalizer()); bus.RegisterHandler(new FileTweetIndexItemDenormalizer()); bus.RegisterHandler(new FileTweetIndexItemDeleteDenormalizer()); bus.RegisterHandler(new ChannelIndexItemDenormalizer()); bus.RegisterHandler(new UserIndexDenormalizer()); bus.RegisterHandler(new UserIndexDeleteDenormalizer()); bus.RegisterHandler(new UserIndexPropertySetDenormalizer()); bus.RegisterHandler(new UserIndexPasswordSetDenormalizer()); bus.RegisterHandler(new UserIndexValidatedDenormalizer()); bus.RegisterHandler(new UserIndexInvalidatedDenormalizer()); bus.RegisterHandler(new UserIndexAddedToRoleDenormalizer()); bus.RegisterHandler(new UserIndexRemovedFromDenormalizer()); return(bus); }
public void InMemoryCommandScheduler_executes_scheduled_commands_immediately_if_no_due_time_is_specified() { // arrange var bus = new InProcessEventBus(); var repository = new InMemoryEventSourcedRepository <Order>(bus: bus); var scheduler = new InMemoryCommandScheduler <Order>(repository); bus.Subscribe(scheduler); var order = CreateOrder(); // act order.Apply(new ShipOn(Clock.Now().Subtract(TimeSpan.FromDays(2)))); repository.Save(order); //assert order = repository.GetLatest(order.Id); var lastEvent = order.Events().Last(); lastEvent.Should().BeOfType <Order.Shipped>(); }
public void When_a_handler_chain_throws_then_an_EventHandlingError_is_published() { // arrange var bus = new InProcessEventBus(); var errors = new List <EventHandlingError>(); bus.Errors.Subscribe(errors.Add); // act var handler = new TestConsequenter() .WrapAll((e, next) => { throw new Exception("oops!"); }); bus.Subscribe(handler); bus.PublishAsync(new Order.Created()).Wait(); // assert errors.Should().ContainSingle(e => e.StreamName == "Order" && e.Event.EventName() == "Created" && e.Exception.Message.Contains("oops!")); }
/// <summary> /// Initializes a new instance of the <see cref="ReadModelCatchup{TDbContext}"/> class. /// </summary> /// <param name="projectors">The projectors to be updated as new events are added to the event store.</param> /// <exception cref="System.ArgumentException">You must specify at least one projector.</exception> public ReadModelCatchup(params object[] projectors) { if (!projectors.OrEmpty().Any()) { throw new ArgumentException("You must specify at least one projector."); } this.projectors = new List <object>(projectors); EnsureProjectorNamesAreDistinct(); cancellationDisposable = new CancellationDisposable(); disposables = new CompositeDisposable { cancellationDisposable, Disposable.Create(() => progress.OnCompleted()) }; bus = new InProcessEventBus(new Subject <IEvent>()); disposables.Add(bus.ReportErrorsToDatabase(() => CreateReadModelDbContext())); disposables.Add(bus); Sensors.ReadModelDbContexts.GetOrAdd(typeof(TDbContext).Name, CreateReadModelDbContext); }
public void When_a_multiple_catch_all_handler_are_registered_for_they_should_all_been_called() { var catchAllEventHandler1 = MockRepository.GenerateMock<IEventHandler<object>>(); var catchAllEventHandler2 = MockRepository.GenerateMock<IEventHandler<object>>(); var catchAllEventHandler3 = MockRepository.GenerateMock<IEventHandler<object>>(); var bus = new InProcessEventBus(); bus.RegisterHandler(catchAllEventHandler1); bus.RegisterHandler(catchAllEventHandler2); bus.RegisterHandler(catchAllEventHandler3); bus.Publish(CreateADomainEvent()); bus.Publish(CreateAEvent()); bus.Publish(CreateAEvent()); bus.Publish(CreateADomainEvent()); bus.Publish(CreateAEvent()); bus.Publish(CreateAEvent()); bus.Publish(CreateAEvent()); catchAllEventHandler1.AssertWasCalled(h => h.Handle(null), options => options.IgnoreArguments().Repeat.Times(7)); catchAllEventHandler2.AssertWasCalled(h => h.Handle(null), options => options.IgnoreArguments().Repeat.Times(7)); catchAllEventHandler3.AssertWasCalled(h => h.Handle(null), options => options.IgnoreArguments().Repeat.Times(7)); }
public async Task InMemoryCommandScheduler_executes_scheduled_commands_immediately_if_no_due_time_is_specified() { // arrange var bus = new InProcessEventBus(); var repository = new InMemoryEventSourcedRepository<Order>(bus: bus); var scheduler = new InMemoryCommandScheduler<Order>(repository); bus.Subscribe(scheduler); var order = CreateOrder(); // act order.Apply(new ShipOn(Clock.Now().Subtract(TimeSpan.FromDays(2)))); await repository.Save(order); await scheduler.Done(); //assert order = await repository.GetLatest(order.Id); var lastEvent = order.Events().Last(); lastEvent.Should().BeOfType<Order.Shipped>(); }
private static IEventBus CreateEventBus() { var bus = new InProcessEventBus(true); return bus; }
public async Task When_one_command_triggers_another_command_via_a_consequenter_then_the_second_command_acquires_the_first_commands_clock() { // arrange var orderId = Any.Guid(); var customerId = Any.Guid(); var bus = new InProcessEventBus(); var orderRepository = new InMemoryEventSourcedRepository<Order>(bus: bus); await orderRepository.Save(new Order(new CreateOrder(Any.FullName()) { AggregateId = orderId, CustomerId = customerId }).Apply(new AddItem { ProductName = Any.Word(), Quantity = 1, Price = Any.Decimal(.01m, 10m) })); var customerRepository = new InMemoryEventSourcedRepository<CustomerAccount>(); await customerRepository.Save(new CustomerAccount(customerId).Apply(new ChangeEmailAddress(Any.Email()))); bus.Subscribe(Consequenter.Create<Order.Shipped>(e => { var order = orderRepository.GetLatest(e.AggregateId).Result; var customer = customerRepository.GetLatest(order.CustomerId).Result; customer.Apply(new SendOrderConfirmationEmail(order.OrderNumber)); customerRepository.Save(customer).Wait(); })); var shipDate = DateTimeOffset.Parse("2014-05-15 01:01:01"); var ship = new Ship(); // act using (CommandContext.Establish(ship, Clock.Create(() => shipDate))) { var order = await orderRepository.GetLatest(orderId); order.Apply(ship); await orderRepository.Save(order); } // assert var last = (await customerRepository.GetLatest(customerId)).Events().Last(); last.Should() .BeOfType<CustomerAccount.OrderShipConfirmationEmailSent>(); last.Timestamp.Should().Be(shipDate); }
private static IEventBus InitializeEventBus() { var bus = new InProcessEventBus(); bus.RegisterAllHandlersInAssembly(typeof(Bootstrapper).Assembly); //bus.RegisterHandler(new InMemoryBufferedEventHandler(buffer)); return bus; }
private static IEventBus InitializeEventBus() { var bus = new InProcessEventBus(); //TODO: need to register handlers here!! bus.RegisterAllHandlersInAssembly(typeof(BuzzyGo.Denormalizer.Card).Assembly); return bus; }
public void When_multiple_messages_are_published_and_a_specific_handler_is_register_oply_the_matching_events_should_be_received_at_the_handler() { var aDomainEventHandler = MockRepository.GenerateMock<IEventHandler<ADomainEvent>>(); var bus = new InProcessEventBus(); bus.RegisterHandler(aDomainEventHandler); var events = new IPublishableEvent[] { CreateAEvent(), CreateADomainEvent(), CreateADomainEvent(), CreateAEvent(), CreateADomainEvent(), CreateAEvent(), CreateAEvent(), CreateADomainEvent(), CreateADomainEvent(), CreateAEvent(), CreateADomainEvent(), CreateAEvent() }; bus.Publish(events); aDomainEventHandler.AssertWasCalled(h => h.Handle(null), options => options.IgnoreArguments().Repeat.Times(6)); }
public void When_a_multiple_specific_handlers_are_register_they_all_should_be_called_when_the_specific_event_is_published() { var specificEventHandler1 = MockRepository.GenerateMock<IEventHandler<ADomainEvent>>(); var specificEventHandler2 = MockRepository.GenerateMock<IEventHandler<ADomainEvent>>(); var specificEventHandler3 = MockRepository.GenerateMock<IEventHandler<ADomainEvent>>(); var bus = new InProcessEventBus(); bus.RegisterHandler(specificEventHandler1); bus.RegisterHandler(specificEventHandler2); bus.RegisterHandler(specificEventHandler3); bus.Publish(CreateADomainEvent()); bus.Publish(CreateAEvent()); bus.Publish(CreateAEvent()); bus.Publish(CreateADomainEvent()); bus.Publish(CreateAEvent()); bus.Publish(CreateAEvent()); bus.Publish(CreateAEvent()); specificEventHandler1.AssertWasCalled(h => h.Handle(null), options => options.IgnoreArguments().Repeat.Times(2)); specificEventHandler2.AssertWasCalled(h => h.Handle(null), options => options.IgnoreArguments().Repeat.Times(2)); specificEventHandler3.AssertWasCalled(h => h.Handle(null), options => options.IgnoreArguments().Repeat.Times(2)); }