Ejemplo n.º 1
0
 public EventReceivePipe(IPipeSpecification <TContext> specification, IPipe <TContext> next, IDependencyScope resolver, MessageHandlerRegistry messageHandlerRegistry)
 {
     _specification          = specification;
     _resolver               = resolver;
     _messageHandlerRegistry = messageHandlerRegistry;
     Next = next;
 }
Ejemplo n.º 2
0
 public RequestPipe(IPipeSpecification <TContext> specification, IPipe <TContext> next, IDependencyScope resolver, MessageHandlerRegistry messageHandlerRegistry)
 {
     Next                    = next;
     _specification          = specification;
     _resolver               = resolver;
     _messageHandlerRegistry = messageHandlerRegistry;
 }
Ejemplo n.º 3
0
        public async Task disposes_consumer_scope_when_consuming_single_message()
        {
            var messageResultStub = new MessageResultBuilder().WithTransportLevelMessage(new TransportLevelMessageBuilder().WithType("foo").Build()).Build();
            var handlerStub       = Dummy.Of <IMessageHandler <FooMessage> >();

            var messageRegistrationStub = new MessageRegistrationBuilder()
                                          .WithHandlerInstanceType(handlerStub.GetType())
                                          .WithMessageInstanceType(typeof(FooMessage))
                                          .WithMessageType("foo")
                                          .Build();

            var spy = new ConsumerScopeSpy(messageResultStub);

            var registry = new MessageHandlerRegistry();

            registry.Register(messageRegistrationStub);

            var consumer = new ConsumerBuilder()
                           .WithConsumerScopeFactory(new ConsumerScopeFactoryStub(spy))
                           .WithUnitOfWork(new UnitOfWorkStub(handlerStub))
                           .WithMessageHandlerRegistry(registry)
                           .Build();

            await consumer.ConsumeSingle(CancellationToken.None);


            Assert.Equal(1, spy.Disposed);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Tell legion to scan for message handlers that are marked with the <see cref="MessageHandlerAttribute"/>.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="assembliesToScan">The assemblies that should be scanned for message handlers (if null only entry assembly is scanned).</param>
        /// <returns></returns>
        public static IDependencyRegistrationContext ScanForMessageHandlers(
            this IDependencyRegistrationContext context,
            IEnumerable <Assembly> assembliesToScan = null)
        {
            if (assembliesToScan == null)
            {
                assembliesToScan = new[] { Assembly.GetEntryAssembly() }.Distinct();
            }

            context.RegisterTransient(
                c => new MessageDispatcher(c.Resolve <IMessageListener>(), c.Resolve <IMessageHandlerRegistry>()),
                typeof(IMessageDispatcher));

            var messageHandlerRegistry = new MessageHandlerRegistry();

            context.RegisterSingleton(c =>
            {
                messageHandlerRegistry.ScanForMessageHandlerTypes(assembliesToScan, t => context.RegisterTransient(t, typeof(IMessageHandler), t));
                var resolutionContext = c.ResolveForLater();
                messageHandlerRegistry.ConnectContainerResolution(t => (IMessageHandler)resolutionContext.Resolve(t));
                return(messageHandlerRegistry);
            });

            return(context);
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Initialises a server login helper.
 /// </summary>
 public ServerLoginHandler(MessageHandlerRegistry messageHandlerRegistry)
 {
     foreach (IBootstrapper bootstrapper in messageHandlerRegistry.Bootstrappers)
     {
         bootstrapper.EntityBootstrapCompleted += EntityBootstrapCompleted;
     }
 }
Ejemplo n.º 6
0
        public async Task expected_order_of_handler_invocation_in_unit_of_work()
        {
            var orderOfInvocation = new LinkedList <string>();

            var dummyMessageResult       = new MessageResultBuilder().WithTransportLevelMessage(new TransportLevelMessageBuilder().WithType("foo").Build()).Build();
            var dummyMessageRegistration = new MessageRegistrationBuilder().WithMessageType("foo").Build();

            var registry = new MessageHandlerRegistry();

            registry.Register(dummyMessageRegistration);

            var sut = new ConsumerBuilder()
                      .WithUnitOfWork(new UnitOfWorkSpy(
                                          handlerInstance: new MessageHandlerSpy <FooMessage>(() => orderOfInvocation.AddLast("during")),
                                          pre: () => orderOfInvocation.AddLast("before"),
                                          post: () => orderOfInvocation.AddLast("after")
                                          ))
                      .WithConsumerScopeFactory(new ConsumerScopeFactoryStub(new ConsumerScopeStub(dummyMessageResult)))
                      .WithMessageHandlerRegistry(registry)
                      .Build();

            await sut.ConsumeSingle(CancellationToken.None);

            Assert.Equal(new[] { "before", "during", "after" }, orderOfInvocation);
        }
        public void GetHandlersReturnHandlerForGivenMessageType()
        {
            IEnumerable <Type> MessageHandlerTypes()
            {
                return(new []
                {
                    typeof(HandlerA),
                    typeof(HandlerB),
                    typeof(NotAHandler)
                });
            }

            var sut = new MessageHandlerRegistry(MessageHandlerTypes);
            var sp  = A.Fake <IServiceProvider>();

            A.CallTo(() => sp.GetService(A <Type> .That.IsEqualTo(typeof(HandlerA)))).Returns(new HandlerA());
            var scope = A.Fake <IServiceScope>();

            A.CallTo(() => scope.ServiceProvider).Returns(sp);

            var handlers = sut.GetHandlers(typeof(MessageA), scope).ToList();

            Assert.NotEmpty(handlers);
            Assert.Single(handlers);
            Assert.Single(handlers, h => h is HandlerA);
        }
Ejemplo n.º 8
0
        public static MessageHandler GetCachedHandlerForMessage <TMessage>(this MessageHandlerRegistry cache)
        {
            var handler = cache.GetHandlersFor(typeof(TMessage)).Single();

            handler.Instance = Activator.CreateInstance(handler.HandlerType);
            return(handler);
        }
Ejemplo n.º 9
0
        public async Task ShouldIndicateWhetherAHandlerIsATimeoutHandler()
        {
            var registry = new MessageHandlerRegistry();

            registry.RegisterHandler(typeof(SagaWithTimeoutOfMessage));

            var handlers = registry.GetHandlersFor(typeof(MyMessage));

            Assert.AreEqual(2, handlers.Count);

            var timeoutHandler = handlers.SingleOrDefault(h => h.IsTimeoutHandler);

            Assert.NotNull(timeoutHandler, "Timeout handler should be marked as such");

            var timeoutInstance = new SagaWithTimeoutOfMessage();

            timeoutHandler.Instance = timeoutInstance;
            await timeoutHandler.Invoke(new MyMessage(), new TestableInvokeHandlerContext());

            Assert.True(timeoutInstance.TimeoutCalled);
            Assert.False(timeoutInstance.HandlerCalled);

            var regularHandler = handlers.SingleOrDefault(h => !h.IsTimeoutHandler);

            Assert.NotNull(regularHandler, "Regular handler should be marked as timeout handler");

            var regularInstance = new SagaWithTimeoutOfMessage();

            regularHandler.Instance = regularInstance;
            await regularHandler.Invoke(new MyMessage(), new TestableInvokeHandlerContext());

            Assert.False(regularInstance.TimeoutCalled);
            Assert.True(regularInstance.HandlerCalled);
        }
Ejemplo n.º 10
0
        public async Task RunNew()
        {
            var cache = new MessageHandlerRegistry(new Conventions());

            cache.RegisterHandler(typeof(StubMessageHandler));
            cache.RegisterHandler(typeof(StubTimeoutHandler));
            var stubMessage    = new StubMessage();
            var stubTimeout    = new StubTimeoutState();
            var messageHandler = cache.GetCachedHandlerForMessage <StubMessage>();
            var timeoutHandler = cache.GetCachedHandlerForMessage <StubTimeoutState>();

            await messageHandler.Invoke(stubMessage, null);

            await timeoutHandler.Invoke(stubTimeout, null);

            var startNew = Stopwatch.StartNew();

            for (var i = 0; i < 100000; i++)
            {
                await messageHandler.Invoke(stubMessage, null);

                await timeoutHandler.Invoke(stubTimeout, null);
            }
            startNew.Stop();
            Trace.WriteLine(startNew.ElapsedMilliseconds);
        }
Ejemplo n.º 11
0
        public async Task WhenProcessMessageMarksMessageWithNoHandlersComplete()
        {
            IEnumerable <Type> MessageHandlerTypes()
            {
                return(new []
                {
                    typeof(HandlerB),
                });
            }

            var scopeFactory = A.Fake <IServiceScopeFactory>();
            var scope        = A.Fake <IServiceScope>();
            var sp           = A.Fake <IServiceProvider>();
            var handler      = A.Fake <HandlerA>();

            A.CallTo(() => sp.GetService(A <Type> .That.IsEqualTo(typeof(HandlerA)))).Returns(handler);

            A.CallTo(() => scopeFactory.CreateScope()).Returns(scope);
            A.CallTo(() => scope.ServiceProvider).Returns(sp);

            var client   = A.Fake <IReceiverClient>();
            var registry = new MessageHandlerRegistry(MessageHandlerTypes);
            var sut      = new MessageDispatcher(scopeFactory, client, registry, new LogCorrelationHandler(false));

            var isCompleted = false;
            await sut.ProcessMessage(typeof(MessageA).FullName, "{aProp1: \"hello\"}", () =>
            {
                isCompleted = true;
                return(Task.CompletedTask);
            }, m => Task.CompletedTask);

            Assert.True(isCompleted, "the markComplete callback was not called");
        }
 public Configuration(LogicalAddress logicalAddress,
                      string queueNameBase,
                      string localAddress,
                      string instanceSpecificQueue,
                      TransportTransactionMode transactionMode,
                      PushRuntimeSettings pushRuntimeSettings,
                      bool purgeOnStartup,
                      Notification <ReceivePipelineCompleted> pipelineCompletedSubscribers,
                      bool isSendOnlyEndpoint,
                      List <Type> executeTheseHandlersFirst,
                      MessageHandlerRegistry messageHandlerRegistry,
                      bool createQueues, TransportSeam transportSeam)
 {
     LogicalAddress               = logicalAddress;
     QueueNameBase                = queueNameBase;
     LocalAddress                 = localAddress;
     InstanceSpecificQueue        = instanceSpecificQueue;
     TransactionMode              = transactionMode;
     PushRuntimeSettings          = pushRuntimeSettings;
     PurgeOnStartup               = purgeOnStartup;
     IsSendOnlyEndpoint           = isSendOnlyEndpoint;
     PipelineCompletedSubscribers = pipelineCompletedSubscribers;
     ExecuteTheseHandlersFirst    = executeTheseHandlersFirst;
     satelliteDefinitions         = new List <SatelliteDefinition>();
     this.messageHandlerRegistry  = messageHandlerRegistry;
     CreateQueues                 = createQueues;
     this.transportSeam           = transportSeam;
 }
Ejemplo n.º 13
0
        public void GetHandlersDoesNotReturnHandlerForGivenMessageTypeIfHandlerIsntARealHandler()
        {
            IEnumerable <Type> MessageHandlerTypes()
            {
                return(new[]
                {
                    typeof(HandlerB),
                    typeof(NotAHandler)
                });
            }

            var sut = new MessageHandlerRegistry(MessageHandlerTypes);
            var sp  = A.Fake <IServiceProvider>();

            A.CallTo(() => sp.GetService(A <Type> .That.IsEqualTo(typeof(NotAHandler)))).Returns(new NotAHandler());

            var scope = A.Fake <IServiceScope>();

            A.CallTo(() => scope.ServiceProvider).Returns(sp);
            var scopeFactory = A.Fake <IServiceScopeFactory>();

            A.CallTo(() => scopeFactory.CreateScope()).Returns(scope);

            var handlers = sut.GetHandlers(scopeFactory, typeof(MessageA)).ToList();

            Assert.Empty(handlers);
        }
Ejemplo n.º 14
0
        public async Task WhenProcessMessageIsCalledWithMessageATheMessageAHandlerIsCalled()
        {
            IEnumerable <Type> MessageHandlerTypes()
            {
                return(new []
                {
                    typeof(HandlerA),
                    typeof(HandlerB),
                    typeof(NotAHandler)
                });
            }

            var scopeFactory = A.Fake <IServiceScopeFactory>();
            var scope        = A.Fake <IServiceScope>();
            var sp           = A.Fake <IServiceProvider>();
            var handler      = A.Fake <HandlerA>();

            A.CallTo(() => handler.Handle(A <MessageA> ._)).Returns(Task.FromResult(HandlerResult.Success()));

            A.CallTo(() => sp.GetService(A <Type> .That.IsEqualTo(typeof(HandlerA)))).Returns(handler);

            A.CallTo(() => scopeFactory.CreateScope()).Returns(scope);
            A.CallTo(() => scope.ServiceProvider).Returns(sp);

            var client   = A.Fake <IReceiverClient>();
            var registry = new MessageHandlerRegistry(MessageHandlerTypes);
            var sut      = new MessageDispatcher(scopeFactory, client, registry, new LogCorrelationHandler(false));

            await sut.ProcessMessage(typeof(MessageA).FullName, "{aProp1: \"hello\"}", () => Task.CompletedTask, m => Task.CompletedTask);

            A.CallTo(() => handler.Handle(A <MessageA> .That.Matches(m => m.AProp1 == "hello")))
            .MustHaveHappenedOnceExactly();
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Scans the given types for types that are message handlers
        /// then uses the Configurer to configure them into the container as single call components,
        /// finally passing them to the bus as its MessageHandlerTypes.
        /// </summary>
        /// <param name="types"></param>
        /// <returns></returns>
        ConfigUnicastBus ConfigureMessageHandlersIn(IEnumerable <Type> types)
        {
            var handlerRegistry = new MessageHandlerRegistry();
            var handlers        = new List <Type>();

            foreach (var t in types.Where(IsMessageHandler))
            {
                Configurer.ConfigureComponent(t, DependencyLifecycle.InstancePerUnitOfWork);
                handlerRegistry.RegisterHandler(t);
                handlers.Add(t);
            }

            Configurer.RegisterSingleton <IMessageHandlerRegistry>(handlerRegistry);

            var availableDispatcherFactories = TypesToScan
                                               .Where(
                factory =>
                !factory.IsInterface && typeof(IMessageDispatcherFactory).IsAssignableFrom(factory))
                                               .ToList();

            var dispatcherMappings = GetDispatcherFactories(handlers, availableDispatcherFactories);

            //configure the message dispatcher for each handler
            busConfig.ConfigureProperty(b => b.MessageDispatcherMappings, dispatcherMappings);
            Configurer.ConfigureProperty <InvokeHandlersBehavior>(b => b.MessageDispatcherMappings, dispatcherMappings);

            availableDispatcherFactories.ToList().ForEach(factory => Configurer.ConfigureComponent(factory, DependencyLifecycle.InstancePerUnitOfWork));

            return(this);
        }
Ejemplo n.º 16
0
        public async Task ExecuteDeferredEvents_WhenCalled_ShouldCallAllEventHandlers()
        {
            // Arrange
            var @event = new FakeEvent { Id = 1 };
            var handlerFactory = new MessageHandlerRegistry();
            var mediator = new Mediator(handlerFactory.MultiInstanceFactory, handlerFactory.SingleInstanceFactory);

            handlerFactory.AddHandlersForEvent(new List<IEventHandler<FakeEvent>>
            {
                _autoSubstitute.SubstituteFor<HandlerDeferringMultipleEvents>(mediator),
                _autoSubstitute.SubstituteFor<HandlerDeferringSingleEvent>(mediator),
                _autoSubstitute.SubstituteFor<HandlerWithoutAdditionalEvents>()
            });

            mediator.DeferEvent(@event);

            // Act
            await mediator.ExecuteDeferredEvents();

            // Assert
            foreach (var handler in handlerFactory.GetHandlersFor<FakeEvent>())
            {
                handler.Received().Handle(Arg.Any<FakeEvent>()).FireAndForget();
            }
        }
Ejemplo n.º 17
0
        public async Task ExecuteDeferredEvents_WhenCalled_ShouldExecuteEventHandlersForEventsFiredInHandlers()
        {
            // Arrange
            var triggerEvent = new FakeEvent { Id = 1 };

            var handlerFactory = new MessageHandlerRegistry();
            var mediator = new Mediator(handlerFactory.MultiInstanceFactory, handlerFactory.SingleInstanceFactory);

            handlerFactory.AddHandlersForEvent(new List<IEventHandler<FakeEvent>>
            {
                new HandlerDeferringMultipleEvents(mediator),
                new HandlerDeferringSingleEvent(mediator),
                new HandlerWithoutAdditionalEvents()
            });

            handlerFactory.AddHandlersForEvent(new List<IEventHandler<FakeEventFromHandler>>
            {
                new DependentEventHandler()
            });

            handlerFactory.AddHandlersForEvent(new List<IEventHandler<FakeEventTwoFromHandler>>
            {
                _autoSubstitute.SubstituteFor<ChainedEventHandler>()
            });

            // Act
            mediator.DeferEvent(triggerEvent);
            await mediator.ExecuteDeferredEvents();

            // Assert
            foreach (var handler in handlerFactory.GetHandlersFor<FakeEventTwoFromHandler>())
            {
                handler.Received(1).Handle(Arg.Any<FakeEventTwoFromHandler>()).FireAndForget();
            }
        }
Ejemplo n.º 18
0
 static List <Type> GetHandledEvents(MessageHandlerRegistry handlerRegistry, Conventions conventions)
 {
     // get all potential messages
     return(handlerRegistry.GetMessageTypes()
            // never auto-route system messages and events
            .Where(t => !conventions.IsInSystemConventionList(t) && conventions.IsEventType(t))
            .ToList());
 }
        static List <Type> GetMessageTypesHandledByThisEndpoint(MessageHandlerRegistry handlerRegistry, Conventions conventions)
        {
            var messageTypesHandled = handlerRegistry.GetMessageTypes()                     //get all potential messages
                                      .Where(t => !conventions.IsInSystemConventionList(t)) //never auto-route system messages
                                      .ToList();

            return(messageTypesHandled);
        }
Ejemplo n.º 20
0
 public ConsumerConfiguration(IDictionary <string, string> configuration, MessageHandlerRegistry messageHandlerRegistry,
                              IHandlerUnitOfWorkFactory unitOfWorkFactory, IConsumerScopeFactory consumerScopeFactory)
 {
     KafkaConfiguration     = configuration;
     MessageHandlerRegistry = messageHandlerRegistry;
     UnitOfWorkFactory      = unitOfWorkFactory;
     ConsumerScopeFactory   = consumerScopeFactory;
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Passes the service the reference to the <see cref="IServiceRegistry" />.
        /// </summary>
        /// <param name="serviceRegistry">Contains a housing for client services.</param>
        public ClientService(IServiceRegistry serviceRegistry)
        {
            messageHandlerRegistry = new MessageHandlerRegistry(serviceRegistry);
            this.serviceRegistry   = serviceRegistry;
            const int minimumMillisecondsAllowedBetweenUserTypingMessages = 1000;

            userTypingThroughputLimiter = new MessageThroughputLimiter <UserTypingRequest>(minimumMillisecondsAllowedBetweenUserTypingMessages);
            userTypingThroughputLimiter.DeferredSendLastMessage += userTypingThroughputLimiter_DeferredSendLastMessage;
        }
Ejemplo n.º 22
0
        public ConsumerBuilder()
        {
            _unitOfWorkFactory = new HandlerUnitOfWorkFactoryStub(null);

            var messageStub = new MessageResultBuilder().Build();

            _consumerScopeFactory = _ => new ConsumerScopeFactoryStub(new ConsumerScopeStub(messageStub));
            _registry             = new MessageHandlerRegistry();
        }
Ejemplo n.º 23
0
        public async Task ExecuteDeferredEvents_WhenCalledWithoutEvent_ShouldNotThrow()
        {
            // Arrange
            var handlerFactory = new MessageHandlerRegistry();
            var mediator = new Mediator(handlerFactory.MultiInstanceFactory, handlerFactory.SingleInstanceFactory);

            // Act
            await mediator.ExecuteDeferredEvents();
        }
Ejemplo n.º 24
0
        public void Should_invoke_handle_method()
        {
            var cache = new MessageHandlerRegistry(new Conventions());

            cache.CacheMethodForHandler(typeof(StubHandler), typeof(StubMessage));
            var handler = new StubHandler();

            cache.InvokeHandle(handler, new StubMessage());
            Assert.IsTrue(handler.HandleCalled);
        }
Ejemplo n.º 25
0
        public void Should_invoke_timeout_method()
        {
            var cache = new MessageHandlerRegistry(new Conventions());

            cache.CacheMethodForHandler(typeof(StubHandler), typeof(StubTimeoutState));
            var handler = new StubHandler();

            cache.InvokeTimeout(handler, new StubTimeoutState());
            Assert.IsTrue(handler.TimeoutCalled);
        }
Ejemplo n.º 26
0
        protected override List<IDispatcher<object>> GetCommandDispatchers(TinyIoCContainer container)
        {
            var widgetCommandHandler = new WidgetCommandHandler(container.Resolve<IAggregateRepository>());

            var typedRegistry = new MessageHandlerRegistry<Type>();
            typedRegistry.AddByConvention(widgetCommandHandler);

            var commandsDispatcher = new RawMessageDispatcher<object>(typedRegistry);

            return new List<IDispatcher<object>> { commandsDispatcher };
        }
Ejemplo n.º 27
0
 public ConsumerBuilder()
 {
     _unitOfWorkFactory    = new HandlerUnitOfWorkFactoryStub(null);
     _consumerScopeFactory =
         _ =>
         new ConsumerScopeFactoryStub(
             new ConsumerScopeStub(
                 new MessageResultBuilder().Build()));
     _registry = new MessageHandlerRegistry();
     _unconfiguredMessageStrategy = new RequireExplicitHandlers();
 }
Ejemplo n.º 28
0
        static List<Type> GetMessageTypesHandledByThisEndpoint(MessageHandlerRegistry handlerRegistry, Conventions conventions, SubscribeSettings settings)
        {
            var messageTypesHandled = handlerRegistry.GetMessageTypes() //get all potential messages
                .Where(t => !conventions.IsInSystemConventionList(t)) //never auto-subscribe system messages
                .Where(t => !conventions.IsCommandType(t)) //commands should never be subscribed to
                .Where(conventions.IsEventType) //only events unless the user asked for all messages
                .Where(t => settings.AutoSubscribeSagas || handlerRegistry.GetHandlersFor(t).Any(handler => !typeof(Saga).IsAssignableFrom(handler.HandlerType))) //get messages with other handlers than sagas if needed
                .ToList();

            return messageTypesHandled;
        }
Ejemplo n.º 29
0
        public void Should_have_passed_through_correct_message()
        {
            var cache = new MessageHandlerRegistry(new Conventions());

            cache.CacheMethodForHandler(typeof(StubHandler), typeof(StubMessage));
            var handler     = new StubHandler();
            var stubMessage = new StubMessage();

            cache.InvokeHandle(handler, stubMessage);
            Assert.AreEqual(stubMessage, handler.HandledMessage);
        }
Ejemplo n.º 30
0
        public async Task Should_invoke_handle_method()
        {
            var cache = new MessageHandlerRegistry(new Conventions());

            cache.RegisterHandler(typeof(StubHandler));

            var handler = cache.GetCachedHandlerForMessage <StubMessage>();
            await handler.Invoke(new StubMessage(), null);

            Assert.IsTrue(((StubHandler)handler.Instance).HandleCalled);
        }
Ejemplo n.º 31
0
 public MyLoadHandlersConnector(
     CurrentSessionHolder sessionHolder,
     MessageHandlerRegistry messageHandlerRegistry,
     ISynchronizedStorage synchronizedStorage,
     ISynchronizedStorageAdapter adapter)
 {
     this.sessionHolder          = sessionHolder;
     this.messageHandlerRegistry = messageHandlerRegistry;
     this.synchronizedStorage    = synchronizedStorage;
     this.adapter = adapter;
 }
Ejemplo n.º 32
0
        static List <Type> GetMessageTypesHandledByThisEndpoint(MessageHandlerRegistry handlerRegistry, Conventions conventions, SubscribeSettings settings)
        {
            var messageTypesHandled = handlerRegistry.GetMessageTypes()                                                                                                                 //get all potential messages
                                      .Where(t => !conventions.IsInSystemConventionList(t))                                                                                             //never auto-subscribe system messages
                                      .Where(t => !conventions.IsCommandType(t))                                                                                                        //commands should never be subscribed to
                                      .Where(t => conventions.IsEventType(t))                                                                                                           //only events unless the user asked for all messages
                                      .Where(t => settings.AutoSubscribeSagas || handlerRegistry.GetHandlersFor(t).Any(handler => !typeof(Saga).IsAssignableFrom(handler.HandlerType))) //get messages with other handlers than sagas if needed
                                      .ToList();

            return(messageTypesHandled);
        }
Ejemplo n.º 33
0
        protected override List<IDispatcher<ResolvedEvent>> GetDispatchers(TinyIoCContainer container)
        {
            var widgetDenormalizer = new WidgetDenormalizer(container.Resolve<IViewModelWriter>());
            var typedRegistry = new MessageHandlerRegistry<Type>();

            typedRegistry.AddByConvention(widgetDenormalizer);

            var aggregateDispatcher = new EventStoreAggregateEventDispatcher(typedRegistry);

            return new List<IDispatcher<ResolvedEvent>>() { aggregateDispatcher };
        }
Ejemplo n.º 34
0
        public async Task Should_invoke_timeout_method()
        {
            var cache = new MessageHandlerRegistry(new Conventions());

            cache.RegisterHandler(typeof(StubHandler));

            var handler        = cache.GetCachedHandlerForMessage <StubTimeoutState>();
            var handlerContext = new TestableMessageHandlerContext();
            await handler.Invoke(new StubTimeoutState(), handlerContext);

            Assert.IsTrue(((StubHandler)handler.Instance).TimeoutCalled);
        }
Ejemplo n.º 35
0
        public async Task Should_have_passed_through_correct_message()
        {
            var cache = new MessageHandlerRegistry(new Conventions());

            cache.RegisterHandler(typeof(StubHandler));

            var handler     = cache.GetCachedHandlerForMessage <StubMessage>();
            var stubMessage = new StubMessage();
            await handler.Invoke(stubMessage, null);

            Assert.AreEqual(stubMessage, ((StubHandler)handler.Instance).HandledMessage);
        }
Ejemplo n.º 36
0
        public async Task Should_have_passed_through_correct_context()
        {
            var cache = new MessageHandlerRegistry(new Conventions());

            cache.RegisterHandler(typeof(StubHandler));

            var handler        = cache.GetCachedHandlerForMessage <StubTimeoutState>();
            var handlerContext = new TestableMessageHandlerContext();
            await handler.Invoke(new StubTimeoutState(), handlerContext);

            Assert.AreSame(handlerContext, ((StubHandler)handler.Instance).HandlerContext);
        }
Ejemplo n.º 37
0
        public async Task ExecuteDeferredEvents_WhenCalledWithoutRegisteredHandlers_ShouldNotCallAnyHandlers()
        {
            // Arrange
            var @event = new FakeEvent { Id = 1 };
            var handlerFactory = new MessageHandlerRegistry();
            var mediator = new Mediator(handlerFactory.MultiInstanceFactory, handlerFactory.SingleInstanceFactory);

            mediator.DeferEvent(@event);

            // Act
            await mediator.ExecuteDeferredEvents();

            // Assert
            foreach (var handler in handlerFactory.GetHandlersFor<FakeEvent>())
            {
                handler.DidNotReceive().Handle(Arg.Any<FakeEvent>()).FireAndForget();
            }
        }
        static void ConfigureMessageHandlersIn(FeatureConfigurationContext context, IEnumerable<Type> types)
        {
            var handlerRegistry = new MessageHandlerRegistry(context.Settings.Get<Conventions>());

            foreach (var t in types.Where(IsMessageHandler))
            {
                context.Container.ConfigureComponent(t, DependencyLifecycle.InstancePerUnitOfWork);
                handlerRegistry.RegisterHandler(t);
            }

            List<Action<IConfigureComponents>> propertiesToInject;
            if (context.Settings.TryGet("NServiceBus.HandlerProperties", out propertiesToInject))
            {
                foreach (var action in propertiesToInject)
                {
                    action(context.Container);
                }
            }

            context.Container.RegisterSingleton(handlerRegistry);
        }
Ejemplo n.º 39
0
        public async Task CommandMissing_ShouldThrowEx()
        {
            var handlerFactory = new MessageHandlerRegistry();
            var mediator = new Mediator(handlerFactory.MultiInstanceFactory, handlerFactory.SingleInstanceFactory);

            handlerFactory.AddHandlersForEvent(new List<IEventHandler<FakeEvent>>
            {
                _autoSubstitute.SubstituteFor<HandlerWithoutAdditionalEvents>()
            });

            await mediator.Send(new CommandMissing { Id = 1 });
        }
Ejemplo n.º 40
0
        public async Task Commands_CanHandleCommandThatFiresOtherCommandsWithAReturnValue()
        {
            // Arrange
            var handlerFactory = new MessageHandlerRegistry();
            var mediator = new Mediator(handlerFactory.MultiInstanceFactory, handlerFactory.SingleInstanceFactory);
            handlerFactory.AddHandlersForCommandOrQuery<ICommandHandler<TestCommandWithResult>>(new TestCommandWithResultHandler(mediator));
            handlerFactory.AddHandlersForCommandOrQuery<ICommandHandler<TestMultipleCommandWithResult>>(new TestMultipleCommandHandlerWithResult(mediator));
           
            // Act
           var result = await mediator.Send(new TestMultipleCommandWithResult { Name = "bar" });

            // Assert
            Assert.IsTrue(result.Result<TestCommandResult>().ResultingValue == 5);
        }
Ejemplo n.º 41
0
        public async Task Commands_CanHandleCommandThatFiresOtherCommandsWithANestedError()
        {
            // Arrange
            var handlerFactory = new MessageHandlerRegistry();
            var mediator = new Mediator(handlerFactory.MultiInstanceFactory, handlerFactory.SingleInstanceFactory);
            handlerFactory.AddHandlersForCommandOrQuery<ICommandHandler<TestCommandWithResult>>(new TestCommandWithResultHandler(mediator));
            handlerFactory.AddHandlersForCommandOrQuery<ICommandHandler<TestMultipleCommandWithResult>>(new TestMultipleCommandHandlerWithResult(mediator));

            // Act
            var result = await mediator.Send(new TestMultipleCommandWithResult { Name = "bar", Id = 999 });

            // Assert
            Assert.IsTrue(result.Result<TestCommandResult>() == null && result.ValidationResults.Any());
        }
Ejemplo n.º 42
0
        public async Task LookupQuery_CanLookupData()
        {
            // Arrange
            var handlerFactory = new MessageHandlerRegistry();
            var mediator = new Mediator(handlerFactory.MultiInstanceFactory, handlerFactory.SingleInstanceFactory);
            handlerFactory.AddHandlersForCommandOrQuery<ILookupQuery<List<FakeResult>>>(new FindResultForLookup());

            // Act
            var result = await mediator.LoadList<List<FakeResult>>();

            // Assert
            Assert.IsTrue(result.Count == FakeDataStore.Results.Count);
        }
Ejemplo n.º 43
0
        public async Task Queries_ShouldAllowMultipleQueryDefinitionsPerObject()
        {
            // Arrange
            var handlerFactory = new MessageHandlerRegistry();
            var mediator = new Mediator(handlerFactory.MultiInstanceFactory, handlerFactory.SingleInstanceFactory);
            handlerFactory.AddHandlersForCommandOrQuery<IQuery<SingleIdCriteria, FakeResult>>(new MultipleQueryTypesInOneObject());
            handlerFactory.AddHandlersForCommandOrQuery<IQuery<SingleNameCriteria, FakeResult>>(new MultipleQueryTypesInOneObject());

            // Act
            var resultByName = await mediator.Query<SingleNameCriteria, FakeResult>(new SingleNameCriteria { Name = "Name2" });
            var resultById = await mediator.Query<SingleIdCriteria, FakeResult>(new SingleIdCriteria { Id = 1 });

            // Assert
            Assert.IsTrue(resultByName.Id == 2);
            Assert.IsTrue(resultById.Id == 1);
        }
Ejemplo n.º 44
0
        public async Task ExecuteDeferredEvents_CanAddFromMultipleThreads()
        {
            var handlerFactory = new MessageHandlerRegistry();
            var mediator = new Mediator(handlerFactory.MultiInstanceFactory, handlerFactory.SingleInstanceFactory);

            handlerFactory.AddHandlersForEvent(new List<IEventHandler<FakeEvent>>
            {
                _autoSubstitute.SubstituteFor<HandlerWithoutAdditionalEvents>()
            });

            var options = new ParallelOptions { MaxDegreeOfParallelism = 10 };

            //Make sure the mediator can handle events being added from multiple threads (should never lose events)
            Parallel.For(0, 10, options, i =>
            {
                for (var j = 0; j < 1000; ++j)
                    mediator.DeferEvent(new FakeEvent { Id = (i * 1000) + j });
            });

            await mediator.ExecuteDeferredEvents();

            foreach (var handler in handlerFactory.GetHandlersFor<FakeEvent>())
            {
                handler.Received(10000).Handle(Arg.Any<FakeEvent>()).FireAndForget();
            }
        }
Ejemplo n.º 45
0
        public async Task Queries_CanReturnPrimitiveTypes()
        {
            // Arrange
            var handlerFactory = new MessageHandlerRegistry();
            var mediator = new Mediator(handlerFactory.MultiInstanceFactory, handlerFactory.SingleInstanceFactory);
            handlerFactory.AddHandlersForCommandOrQuery<IQuery<SingleNameCriteria, int>>(new FindPrimitiveTypeByCriteria());

            // Act
            var result = await mediator.Query<SingleNameCriteria, int>(new SingleNameCriteria { Name = "Name1" });

            // Assert
            Assert.IsTrue(result == 1);
        }
Ejemplo n.º 46
0
        public async Task Queries_WhenCalledWithPrimitiveCriteria_ShouldReturnResult()
        {
            // Arrange
            var handlerFactory = new MessageHandlerRegistry();
            var mediator = new Mediator(handlerFactory.MultiInstanceFactory, handlerFactory.SingleInstanceFactory);
            handlerFactory.AddHandlersForCommandOrQuery<IQuery<int, List<FakeResult>>>(new FindFakeResultByPrimitiveType());

            // Act
            var result = await mediator.Query<int, List<FakeResult>>(1);

            // Assert
            Assert.IsTrue(result.FirstOrDefault() != null);
            Assert.IsTrue(result.First().Id == 1);
        }
Ejemplo n.º 47
0
        public async Task Queries_WhenCalledWithCriteria_ShouldReturnResult()
        {
            // Arrange
            var handlerFactory = new MessageHandlerRegistry();
            var mediator = new Mediator(handlerFactory.MultiInstanceFactory, handlerFactory.SingleInstanceFactory);
            handlerFactory.AddHandlersForCommandOrQuery<IQuery<FakeRangeCriteria, List<FakeResult>>>(new FindFakeResultByRangeCriteria());

            // Act
            var result = await mediator.Query<FakeRangeCriteria, List<FakeResult>>(new FakeRangeCriteria { MinValue = 0, MaxValue = 5 });

            // Assert
            Assert.IsTrue(result.Count == 5);
        }
Ejemplo n.º 48
0
        public async Task Commands_WhenExecuting_CanSuccessfulCompleteValidCommand()
        {
            // Arrange
            var handlerFactory = new MessageHandlerRegistry();
            var mediator = new Mediator(handlerFactory.MultiInstanceFactory, handlerFactory.SingleInstanceFactory);
            handlerFactory.AddHandlersForCommandOrQuery<ICommandHandler<TestCommand>>(new TestCommandHandler(mediator));

            // Act
            var result = await mediator.Send(new TestCommand { Id = 1 });

            // Assert
            Assert.IsFalse(result.ValidationResults.Any());
        }
Ejemplo n.º 49
0
        public async Task Commands_CanHandleCommandWithAReturnValueWithValidationFailures()
        {
            // Arrange
            var handlerFactory = new MessageHandlerRegistry();
            var mediator = new Mediator(handlerFactory.MultiInstanceFactory, handlerFactory.SingleInstanceFactory);
            handlerFactory.AddHandlersForCommandOrQuery<ICommandHandler<TestCommandWithResult>>(new TestCommandWithResultHandler(mediator));

            // Act
            var result = await mediator.Send(new TestCommandWithResult { Id = 999 });
            var returnedValue = result.Result<TestCommandResult>();

            // Assert
            Assert.IsTrue(returnedValue == null && result.ValidationResults.Any());
        }
Ejemplo n.º 50
-1
        public async Task DeferEvents_CanDeferMultipleEvents()
        {
            // Arrange
            var handlerFactory = new MessageHandlerRegistry();
            var mediator = new Mediator(handlerFactory.MultiInstanceFactory, handlerFactory.SingleInstanceFactory);
            handlerFactory.AddHandlersForEvent(new List<IEventHandler<FakeEvent>>
            {
                Substitute.For<HandlerDeferringMultipleEvents>(mediator),
                Substitute.For<HandlerDeferringSingleEvent>(mediator),
                Substitute.For<HandlerWithoutAdditionalEvents>()
            });

            handlerFactory.AddHandlersForEvent(new List<IEventHandler<FakeEventFromHandler>>
            {
                Substitute.For<DependentEventHandler>()
            });

            handlerFactory.AddHandlersForCommandOrQuery<ICommandHandler<TestCommand>>(new TestCommandHandler(mediator));

            // Act
            var result = await mediator.Send(new TestCommand { Id = 1 });
            Assert.IsFalse(result.ValidationResults.Any());

            // Assert
            foreach (var handler in handlerFactory.GetHandlersFor<FakeEvent>())
            {
                handler.Received().Handle(Arg.Any<FakeEvent>()).FireAndForget();
            }

            foreach (var handler in handlerFactory.GetHandlersFor<FakeEventFromHandler>())
            {
                handler.Received().Handle(Arg.Any<FakeEventFromHandler>()).FireAndForget();
            }
        }