Beispiel #1
0
        public async Task CustomMessageHandler_WithContextFilter_UsesMessageTypeDuringSelection()
        {
            // Arrange
            var spyHandler = new StubTestMessageHandler <Purchase, MessageContext>();

            var collection = new MessageHandlerCollection(new ServiceCollection());

            collection.WithMessageHandler <StubTestMessageHandler <Order, MessageContext>, Order>();
            collection.WithMessageHandler <StubTestMessageHandler <Purchase, TestMessageContext>, Purchase, TestMessageContext>();
            collection.WithMessageHandler <StubTestMessageHandler <Purchase, MessageContext>, Purchase>(provider => spyHandler);

            IServiceProvider serviceProvider = collection.Services.BuildServiceProvider();
            var router = new TestMessageRouter(serviceProvider, _logger);

            var purchase = new Purchase
            {
                CustomerName = _bogusGenerator.Name.FullName(),
                Price        = _bogusGenerator.Commerce.Price()
            };
            string purchaseJson    = JsonConvert.SerializeObject(purchase);
            var    context         = new MessageContext("message-id", new Dictionary <string, object>());
            var    correlationInfo = new MessageCorrelationInfo("operation-id", "transaction-id");

            // Act
            await router.RouteMessageAsync(purchaseJson, context, correlationInfo, CancellationToken.None);

            // Assert
            Assert.True(spyHandler.IsProcessed);
        }
Beispiel #2
0
        public async Task CustomMessageHandler_WithContextFilter_UsesFilterDuringSelection()
        {
            // Arrange
            var messageId = Guid.NewGuid().ToString();
            var message   = new TestMessage {
                TestProperty = Guid.NewGuid().ToString()
            };
            string messageJson     = JsonConvert.SerializeObject(message);
            var    context         = new TestMessageContext(messageId, new Dictionary <string, object>());
            var    correlationInfo = new MessageCorrelationInfo("operation-id", "transaction-id");
            var    spyHandler1     = new TestMessageHandler();
            var    spyHandler2     = new TestMessageHandler();

            var collection = new MessageHandlerCollection(new ServiceCollection());

            collection.WithMessageHandler <TestMessageHandler, TestMessage, TestMessageContext>(
                messageContextFilter: ctx => ctx.MessageId == "some other ID",
                implementationFactory: provider => spyHandler2);
            collection.WithMessageHandler <TestMessageHandler, TestMessage, TestMessageContext>(
                messageContextFilter: ctx => ctx.MessageId == messageId,
                implementationFactory: provider => spyHandler1);
            collection.WithMessageHandler <TestMessageHandler, TestMessage, TestMessageContext>();
            collection.WithMessageHandler <DefaultTestMessageHandler, TestMessage>();

            IServiceProvider serviceProvider = collection.Services.BuildServiceProvider();
            var router = new TestMessageRouter(serviceProvider, _logger);

            // Act
            await router.RouteMessageAsync(messageJson, context, correlationInfo, CancellationToken.None);

            // Assert
            Assert.True(spyHandler1.IsProcessed);
            Assert.False(spyHandler2.IsProcessed);
        }
Beispiel #3
0
        public async Task WithMessageHandlerWithDefaultContext_WithMessageBodySerializerImplementationFactoryWithMessageBodyFilter_UsesSerializer(bool matches)
        {
            // Arrange
            var services        = new MessageHandlerCollection(new ServiceCollection());
            var expectedBody    = $"test-message-body-{Guid.NewGuid()}";
            var expectedMessage = new TestMessage();
            var serializer      = new TestMessageBodySerializer(expectedBody, expectedMessage);

            // Act
            services.WithMessageHandler <DefaultTestMessageHandler, TestMessage>(
                messageBodySerializerImplementationFactory: serviceProvider => serializer,
                messageBodyFilter: body =>
            {
                Assert.Same(expectedMessage, body);
                return(matches);
            });

            // Assert
            IServiceProvider             provider = services.Services.BuildServiceProvider();
            IEnumerable <MessageHandler> handlers = MessageHandler.SubtractFrom(provider, NullLogger.Instance);

            Assert.NotNull(handlers);
            MessageHandler handler = Assert.Single(handlers);

            Assert.NotNull(handler);
            bool actual = handler.CanProcessMessageBasedOnMessage(expectedMessage);

            Assert.Equal(matches, actual);
            MessageResult result = await handler.TryCustomDeserializeMessageAsync(expectedBody);

            Assert.NotNull(result);
            Assert.Same(expectedMessage, result.DeserializedMessage);
        }
Beispiel #4
0
        public async Task CustomMessageHandlerFactory_WithCustomContext_SubtractsRegistration()
        {
            // Arrange
            var spyHandler = new TestMessageHandler();

            var collection = new MessageHandlerCollection(new ServiceCollection());

            collection.WithMessageHandler <TestMessageHandler, TestMessage, TestMessageContext>(provider => spyHandler);
            IServiceProvider serviceProvider = collection.Services.BuildServiceProvider();

            // Act
            IEnumerable <MessageHandler> messageHandlers = MessageHandler.SubtractFrom(serviceProvider, _logger);

            // Assert
            MessageHandler messageHandler = Assert.Single(messageHandlers);

            Assert.NotNull(messageHandler);

            var message         = new TestMessage();
            var context         = TestMessageContext.Generate();
            var correlationInfo = new MessageCorrelationInfo("operation-id", "transaction-id");
            await messageHandler.ProcessMessageAsync(message, context, correlationInfo, CancellationToken.None);

            Assert.True(spyHandler.IsProcessed);
        }
Beispiel #5
0
        public void CustomMessageHandlerFactory_WithMessageBodyAndContextFilter_SubtractsRegistration(bool matchesBody, bool matchesContext)
        {
            // Arrange
            var collection = new MessageHandlerCollection(new ServiceCollection());
            var spyHandler = new TestMessageHandler();

            collection.WithMessageHandler <TestMessageHandler, TestMessage, TestMessageContext>(
                (TestMessageContext messageContext) => matchesContext,
                (TestMessage messageBody) => matchesBody,
                provider => spyHandler);
            ServiceProvider serviceProvider = collection.Services.BuildServiceProvider();

            // Act
            IEnumerable <MessageHandler> messageHandlers = MessageHandler.SubtractFrom(serviceProvider, _logger);

            // Assert
            MessageHandler messageHandler = Assert.Single(messageHandlers);

            Assert.NotNull(messageHandler);

            var context = TestMessageContext.Generate();

            Assert.Equal(matchesContext, messageHandler.CanProcessMessageBasedOnContext(messageContext: context));
            Assert.Equal(matchesBody, messageHandler.CanProcessMessageBasedOnMessage(new TestMessage()));
        }
        public async Task WithMessageHandlerWithDefaultContext_WithMessageBodySerializerWithImplementationFactory_UsesSerializer()
        {
            // Arrange
            var services        = new MessageHandlerCollection(new ServiceCollection());
            var expectedBody    = $"test-message-body-{Guid.NewGuid()}";
            var expectedMessage = new TestMessage();
            var serializer      = new TestMessageBodySerializer(expectedBody, expectedMessage);
            var expectedHandler = new DefaultTestMessageHandler();

            // Act
            services.WithMessageHandler <DefaultTestMessageHandler, TestMessage>(
                messageBodySerializer: serializer, implementationFactory: serviceProvider => expectedHandler);

            // Assert
            IServiceProvider             provider = services.Services.BuildServiceProvider();
            IEnumerable <MessageHandler> handlers = MessageHandler.SubtractFrom(provider, NullLogger.Instance);

            Assert.NotNull(handlers);
            MessageHandler handler = Assert.Single(handlers);

            Assert.NotNull(handler);
            Assert.NotSame(expectedHandler, handler);
            MessageResult result = await handler.TryCustomDeserializeMessageAsync(expectedBody);

            Assert.NotNull(result);
            Assert.Same(expectedMessage, result.DeserializedMessage);
        }
Beispiel #7
0
        public void WithMessageHandlerWithDefaultContext_WithMessageContextFilterWithMessageBodyFilterWithImplementationFactory_UsesSerializer(bool matchesContext, bool matchesBody)
        {
            // Arrange
            var services        = new MessageHandlerCollection(new ServiceCollection());
            var expectedMessage = new TestMessage();
            var expectedContext = new MessageContext($"message-id-{Guid.NewGuid()}", new Dictionary <string, object>());
            var expectedHandler = new DefaultTestMessageHandler();

            // Act
            services.WithMessageHandler <DefaultTestMessageHandler, TestMessage>(
                messageContextFilter: context =>
            {
                Assert.Same(expectedContext, context);
                return(matchesContext);
            },
                messageBodyFilter: body =>
            {
                Assert.Same(expectedMessage, body);
                return(matchesBody);
            },
                implementationFactory: serviceProvider => expectedHandler);

            // Assert
            IServiceProvider             provider = services.Services.BuildServiceProvider();
            IEnumerable <MessageHandler> handlers = MessageHandler.SubtractFrom(provider, NullLogger.Instance);

            Assert.NotNull(handlers);
            MessageHandler handler = Assert.Single(handlers);

            Assert.NotNull(handler);
            Assert.NotSame(expectedHandler, handler);
            Assert.Equal(matchesContext, handler.CanProcessMessageBasedOnContext(expectedContext));
            Assert.Equal(matchesBody, handler.CanProcessMessageBasedOnMessage(expectedMessage));
        }
Beispiel #8
0
        public void WithMessageHandlerWithCustomContext_WithMessageContextFilterWithMessageBodyFilter_UsesSerializer(bool matchesContext, bool matchesBody)
        {
            // Arrange
            var services        = new MessageHandlerCollection(new ServiceCollection());
            var expectedMessage = new TestMessage();
            var expectedContext = TestMessageContext.Generate();
            var expectedHandler = new DefaultTestMessageHandler();

            // Act
            services.WithMessageHandler <TestMessageHandler, TestMessage, TestMessageContext>(
                messageContextFilter: context =>
            {
                Assert.Same(expectedContext, context);
                return(matchesContext);
            },
                messageBodyFilter: body =>
            {
                Assert.Same(expectedMessage, body);
                return(matchesBody);
            });

            // Assert
            IServiceProvider             provider = services.Services.BuildServiceProvider();
            IEnumerable <MessageHandler> handlers = MessageHandler.SubtractFrom(provider, NullLogger.Instance);

            Assert.NotNull(handlers);
            MessageHandler handler = Assert.Single(handlers);

            Assert.NotNull(handler);
            Assert.NotSame(expectedHandler, handler);
            Assert.Equal(matchesContext, handler.CanProcessMessageBasedOnContext(expectedContext));
            Assert.Equal(matchesBody, handler.CanProcessMessageBasedOnMessage(expectedMessage));
        }
Beispiel #9
0
        public void WithMessageHandlerDefaultContext_WithMessageBodyFilterWithImplementationFactory_UsesFilter(bool matches)
        {
            // Arrange
            var services        = new MessageHandlerCollection(new ServiceCollection());
            var expectedHandler = new DefaultTestMessageHandler();
            var message         = new TestMessage();

            // Act
            services.WithMessageHandler <DefaultTestMessageHandler, TestMessage>(messageBodyFilter: body =>
            {
                Assert.Same(message, body);
                return(matches);
            }, implementationFactory: serviceProvider => expectedHandler);

            // Assert
            IServiceProvider             provider = services.Services.BuildServiceProvider();
            IEnumerable <MessageHandler> handlers = MessageHandler.SubtractFrom(provider, NullLogger.Instance);
            MessageHandler handler = Assert.Single(handlers);

            Assert.NotNull(handler);
            Assert.NotSame(expectedHandler, handler);
            bool actual = handler.CanProcessMessageBasedOnMessage(message);

            Assert.Equal(matches, actual);
        }
Beispiel #10
0
        public async Task WithMessageRouting_WithMessageHandlerContextFilter_GoesThroughRegisteredMessageHandlers()
        {
            // Arrange
            var services               = new ServiceCollection();
            var collection             = new MessageHandlerCollection(services);
            var spyHandler             = new StubTestMessageHandler <TestMessage, TestMessageContext>();
            var ignoredSameTypeHandler = new StubTestMessageHandler <TestMessage, TestMessageContext>();

            var ignoredDefaultHandler = new DefaultTestMessageHandler();
            var ignoredHandler        = new TestMessageHandler();

            collection.WithMessageHandler <DefaultTestMessageHandler, TestMessage>(serviceProvider => ignoredDefaultHandler)
            .WithMessageHandler <StubTestMessageHandler <TestMessage, TestMessageContext>, TestMessage, TestMessageContext>(
                messageContextFilter: ctx => false, implementationFactory: serviceProvider => ignoredSameTypeHandler)
            .WithMessageHandler <StubTestMessageHandler <TestMessage, TestMessageContext>, TestMessage, TestMessageContext>(serviceProvider => spyHandler)
            .WithMessageHandler <TestMessageHandler, TestMessage, TestMessageContext>(serviceProvider => ignoredHandler);

            // Act
            services.AddMessageRouting();

            // Assert
            IServiceProvider provider = services.BuildServiceProvider();
            var router = provider.GetRequiredService <IMessageRouter>();

            var    correlationInfo = new MessageCorrelationInfo("operation-id", "transaction-id");
            var    context         = TestMessageContext.Generate();
            string json            = JsonConvert.SerializeObject(new TestMessage());
            await router.RouteMessageAsync(json, context, correlationInfo, CancellationToken.None);

            Assert.True(spyHandler.IsProcessed);
            Assert.False(ignoredSameTypeHandler.IsProcessed);
            Assert.False(ignoredDefaultHandler.IsProcessed);
            Assert.False(ignoredHandler.IsProcessed);
        }
Beispiel #11
0
        public IStartableBus CreateBus()
        {
            if (this.ServiceLocator == null)
            {
                throw new InvalidConfigurationException("A ServiceLocator instance must be specified.");
            }

            var messageTypes  = MessageTypeConventions.ScanAssembliesForMessageTypes(AssembliesToScan);
            var messageMapper = new MessageMapper(MessageTypeConventions);

            messageMapper.Initialize(messageTypes);
            var messageHandlers = new MessageHandlerCollection(MessageTypeConventions);

            messageHandlers.ScanAssembliesAndInitialize(AssembliesToScan);

            var staticRoutes = new Dictionary <Type, string>();

            foreach (var mapping in MessageEndpointMappings.OrderByDescending(m => m))
            {
                mapping.Configure((messageType, endpoint) =>
                {
                    if (!MessageTypeConventions.IsMessageType(messageType))
                    {
                        return;
                    }
                    staticRoutes[messageType] = endpoint;
                    logger.Debug("Mapping message type [{0}] to endpoint [{1}]", messageType.FullName, endpoint);
                });
            }

            return(new LightRailServiceBus(this, messageMapper, messageHandlers, staticRoutes));
        }
        public async Task WithMessageRouting_WithIgnoreMissingMembers_GoesThroughDifferentMessageHandler(AdditionalMemberHandling additionalMemberHandling)
        {
            // Arrange
            var services         = new ServiceCollection();
            var collection       = new MessageHandlerCollection(services);
            var messageHandlerV1 = new OrderV1MessageHandler();
            var messageHandlerV2 = new OrderV2MessageHandler();

            collection.WithMessageHandler <OrderV1MessageHandler, Order>(provider => messageHandlerV1)
            .WithMessageHandler <OrderV2MessageHandler, OrderV2>(provider => messageHandlerV2);

            // Act
            services.AddMessageRouting(options => options.Deserialization.AdditionalMembers = additionalMemberHandling);

            // Assert
            IServiceProvider serviceProvider = services.BuildServiceProvider();
            var router = serviceProvider.GetRequiredService <IMessageRouter>();

            OrderV2 order           = OrderV2Generator.Generate();
            var     context         = new MessageContext("message-id", new Dictionary <string, object>());
            var     correlationInfo = new MessageCorrelationInfo("operation-id", "transaction-id");
            string  json            = JsonConvert.SerializeObject(order);

            await router.RouteMessageAsync(json, context, correlationInfo, CancellationToken.None);

            Assert.Equal(additionalMemberHandling is AdditionalMemberHandling.Ignore, messageHandlerV1.IsProcessed);
            Assert.Equal(additionalMemberHandling is AdditionalMemberHandling.Error, messageHandlerV2.IsProcessed);
        }
        /// <summary>
        /// Adds a <see cref="IMessageHandler{TMessage, TMessageContext}" /> implementation to process the messages from an Azure Service Bus.
        /// resources.
        /// </summary>
        /// <typeparam name="TMessageHandler">The type of the implementation.</typeparam>
        /// <typeparam name="TMessage">The type of the message that the message handler will process.</typeparam>
        /// <typeparam name="TMessageContext">The type of the context in which the message handler will process the message.</typeparam>
        /// <param name="services">The collection of services to use in the application.</param>
        /// <param name="messageContextFilter">The function that determines if the message handler should handle the message based on the context.</param>
        /// <param name="messageBodySerializerImplementationFactory">The function to create an custom <see cref="IMessageBodySerializer"/> to deserialize the incoming message for the <typeparamref name="TMessageHandler"/>.</param>
        /// <param name="messageBodyFilter">The filter to restrict the message processing based on the incoming message body.</param>
        /// <param name="messageHandlerImplementationFactory">The function that creates the message handler.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="services"/>, <paramref name="messageBodyFilter"/>, or <paramref name="messageHandlerImplementationFactory"/> is <c>null</c>.</exception>
        public static MessageHandlerCollection WithMessageHandler <TMessageHandler, TMessage, TMessageContext>(
            this MessageHandlerCollection services,
            Func <TMessageContext, bool> messageContextFilter,
            Func <IServiceProvider, IMessageBodySerializer> messageBodySerializerImplementationFactory,
            Func <TMessage, bool> messageBodyFilter,
            Func <IServiceProvider, TMessageHandler> messageHandlerImplementationFactory)
            where TMessageHandler : class, IMessageHandler <TMessage, TMessageContext>
            where TMessage : class
            where TMessageContext : MessageContext
        {
            Guard.NotNull(services, nameof(services), "Requires a set of services to add the message handler");
            Guard.NotNull(messageContextFilter, nameof(messageContextFilter), "Requires a filter to restrict the message processing within a certain message context");
            Guard.NotNull(messageBodySerializerImplementationFactory, nameof(messageBodySerializerImplementationFactory), "Requires a function to create an custom message body serializer instance to deserialize incoming message for the message handler");
            Guard.NotNull(messageBodyFilter, nameof(messageBodyFilter), "Requires a filter to restrict the message processing based on the incoming message body");
            Guard.NotNull(messageHandlerImplementationFactory, nameof(messageHandlerImplementationFactory), "Requires a function to create the message handler with dependent services");

            services.Services.AddTransient <IMessageHandler <TMessage, TMessageContext>, MessageHandlerRegistration <TMessage, TMessageContext> >(
                serviceProvider => new MessageHandlerRegistration <TMessage, TMessageContext>(
                    messageContextFilter: messageContextFilter,
                    messageBodySerializer: messageBodySerializerImplementationFactory(serviceProvider),
                    messageBodyFilter: messageBodyFilter,
                    messageHandlerImplementation: messageHandlerImplementationFactory(serviceProvider),
                    logger: serviceProvider.GetService <ILogger <MessageHandlerRegistration <TMessage, TMessageContext> > >()));

            return(services);
        }
Beispiel #14
0
 public MessageParser(AppConfig appConfig, ISignalHandler signal, MessageHandlerCollection handlers, ConcurrentQueue <PipeMessageEx> queue)
 {
     _appConfig    = appConfig;
     this.signal   = signal;
     this.handlers = handlers ?? new MessageHandlerCollection();
     this.queue    = queue;
 }
        public void WithMessageHandlerTMessageHandlerTMessage_WithoutMessageContextFilterWithMessageBodyFilter_Fails()
        {
            // Arrange
            var services = new MessageHandlerCollection(new ServiceCollection());

            // Act / Assert
            Assert.ThrowsAny <ArgumentException>(() => services.WithMessageHandler <DefaultTestMessageHandler, TestMessage>(messageContextFilter: null, messageBodyFilter: body => true));
        }
Beispiel #16
0
        public void WithMessageHandlerCustomContext_WithoutMessageBodyFilter_Fails()
        {
            // Arrange
            var services = new MessageHandlerCollection(new ServiceCollection());

            // Act / Assert
            Assert.ThrowsAny <ArgumentException>(() => services.WithMessageHandler <TestMessageHandler, TestMessage, TestMessageContext>(messageBodyFilter: null));
        }
        /// <summary>
        /// Adds a <see cref="MessageRouter"/> implementation to route the incoming messages through registered <see cref="IMessageHandler{TMessage}"/> instances.
        /// </summary>
        /// <param name="services">The collection of services to add the router to.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="services"/> is <c>null</c>.</exception>
        public static MessageHandlerCollection AddMessageRouting(this IServiceCollection services)
        {
            Guard.NotNull(services, nameof(services), "Requires a set of services to add the message routing");

            MessageHandlerCollection collection = AddMessageRouting(services, configureOptions: null);

            return(collection);
        }
        public void WithMessageHandlerWithDefaultContext_WithoutMessageBodySerializer_Fails()
        {
            // Arrange
            var services = new MessageHandlerCollection(new ServiceCollection());

            // Act / Assert
            Assert.ThrowsAny <ArgumentException>(
                () => services.WithMessageHandler <DefaultTestMessageHandler, TestMessage>(messageBodySerializer: null));
        }
Beispiel #19
0
        public void WithMessageHandlerDefaultContext_WithMessageBodyFilterWithoutImplementationFactory_Fails()
        {
            // Arrange
            var services = new MessageHandlerCollection(new ServiceCollection());

            // Act / Assert
            Assert.ThrowsAny <ArgumentException>(() => services.WithMessageHandler <DefaultTestMessageHandler, TestMessage>(
                                                     messageBodyFilter: body => true, implementationFactory: null));
        }
Beispiel #20
0
        public void WithMessageHandlerCustomContext_WithoutMessageBodyFilterWithImplementationFactory_Fails()
        {
            // Arrange
            var services = new MessageHandlerCollection(new ServiceCollection());

            // Act / Assert
            Assert.ThrowsAny <ArgumentException>(() => services.WithMessageHandler <TestMessageHandler, TestMessage, TestMessageContext>(
                                                     messageBodyFilter: null, implementationFactory: serviceProvider => new TestMessageHandler()));
        }
        public void WithFallbackMessageHandlerImplementationFunction_WithoutImplementationFunction_Throws()
        {
            // Arrange
            var services = new MessageHandlerCollection(new ServiceCollection());

            // Act / Assert
            Assert.ThrowsAny <ArgumentException>(
                () => services.WithFallbackMessageHandler(createImplementation: (Func <IServiceProvider, PassThruFallbackMessageHandler>)null));
        }
Beispiel #22
0
        public void WithFallbackMessageHandler_WithoutImplementationFactory_Fails()
        {
            // Arrange
            var services = new MessageHandlerCollection(new ServiceCollection());

            // Act / Assert
            Assert.ThrowsAny <ArgumentException>(
                () => services.WithFallbackMessageHandler <PassThruFallbackMessageHandler>(createImplementation: null));
        }
        public void WithMessageHandlerTMessageHandlerTMessage_WithImplementationFactoryWithMessageContextFilterWithoutMessageBodyFilter_Fails()
        {
            // Arrange
            var services = new MessageHandlerCollection(new ServiceCollection());

            // Act / Assert
            Assert.ThrowsAny <ArgumentException>(
                () => services.WithMessageHandler <DefaultTestMessageHandler, TestMessage>(
                    context => true, messageBodyFilter: null, implementationFactory: serviceProvider => new DefaultTestMessageHandler()));
        }
        public void WithMessageHandlerWithCustomContext_WithMessageBodySerializerWithoutImplementationFactory_Fails()
        {
            // Arrange
            var services = new MessageHandlerCollection(new ServiceCollection());

            // Act / Assert
            Assert.ThrowsAny <ArgumentException>(
                () => services.WithMessageHandler <TestMessageHandler, TestMessage, TestMessageContext>(
                    messageBodySerializer: Mock.Of <IMessageBodySerializer>(), implementationFactory: null));
        }
Beispiel #25
0
        /// <summary>
        /// Adds an <see cref="IFallbackMessageHandler"/> implementation which the message pump can use to fall back to when no message handler is found to process the message.
        /// </summary>
        /// <typeparam name="TMessageHandler">The type of the fallback message handler.</typeparam>
        /// <param name="collection">The collection to add the fallback message handler to.</param>
        /// <param name="createImplementation">The function to create the fallback message handler.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="collection"/> or the <paramref name="createImplementation"/> is <c>null</c>.</exception>
        public static MessageHandlerCollection WithFallbackMessageHandler <TMessageHandler>(
            this MessageHandlerCollection collection,
            Func <IServiceProvider, TMessageHandler> createImplementation)
            where TMessageHandler : class, IFallbackMessageHandler
        {
            Guard.NotNull(collection, nameof(collection), "Requires a collection collection to add the fallback message handler to");
            Guard.NotNull(createImplementation, nameof(createImplementation), "Requires a function to create the fallback message handler");

            collection.Services.AddSingleton <IFallbackMessageHandler, TMessageHandler>(createImplementation);
            return(collection);
        }
Beispiel #26
0
        public void WithMessageHandlerWithCustomContext_WithoutMessageBodySerializerImplementationFactoryWithMessageBodyFilter_Fails()
        {
            // Arrange
            var services = new MessageHandlerCollection(new ServiceCollection());

            // Act / Assert
            Assert.ThrowsAny <ArgumentException>(
                () => services.WithMessageHandler <TestMessageHandler, TestMessage, TestMessageContext>(
                    messageBodySerializerImplementationFactory: null,
                    messageBodyFilter: body => true));
        }
Beispiel #27
0
        /// <summary>
        /// Adds a <see cref="IMessageHandler{TMessage}" /> implementation to process the messages from an Azure Service Bus.
        /// resources.
        /// </summary>
        /// <typeparam name="TMessageHandler">The type of the implementation.</typeparam>
        /// <typeparam name="TMessage">The type of the message that the message handler will process.</typeparam>
        /// <param name="services">The collection of services to use in the application.</param>
        /// <param name="messageContextFilter">The function that determines if the message handler should handle the message based on the context.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="services"/> or <paramref name="messageContextFilter"/> is <c>null</c>.</exception>
        public static MessageHandlerCollection WithMessageHandler <TMessageHandler, TMessage>(
            this MessageHandlerCollection services,
            Func <MessageContext, bool> messageContextFilter)
            where TMessageHandler : class, IMessageHandler <TMessage, MessageContext>
            where TMessage : class
        {
            Guard.NotNull(services, nameof(services), "Requires a set of services to add the message handler");
            Guard.NotNull(messageContextFilter, nameof(messageContextFilter), "Requires a filter to restrict the message processing within a certain message context");

            return(services.WithMessageHandler <TMessageHandler, TMessage, MessageContext>(messageContextFilter));
        }
        /// <summary>
        /// Adds a <see cref="IMessageHandler{TMessage}" /> implementation to process the messages from an Azure Service Bus.
        /// resources.
        /// </summary>
        /// <typeparam name="TMessageHandler">The type of the implementation.</typeparam>
        /// <typeparam name="TMessage">The type of the message that the message handler will process.</typeparam>
        /// <param name="services">The collection of services to use in the application.</param>
        /// <param name="messageBodySerializer">The custom <see cref="IMessageBodySerializer"/> to deserialize the incoming message for the <typeparamref name="TMessageHandler"/>.</param>
        public static MessageHandlerCollection WithMessageHandler <TMessageHandler, TMessage>(
            this MessageHandlerCollection services,
            IMessageBodySerializer messageBodySerializer)
            where TMessageHandler : class, IMessageHandler <TMessage, MessageContext>
            where TMessage : class
        {
            Guard.NotNull(services, nameof(services), "Requires a set of services to add the message handler");
            Guard.NotNull(messageBodySerializer, nameof(messageBodySerializer), "Requires an custom message body serializer instance to deserialize incoming message for the message handler");

            return(services.WithMessageHandler <TMessageHandler, TMessage, MessageContext>(messageBodySerializer));
        }
        public void WithMessageHandlerWithDefaultContext_WithMessageBodySerializerImplementationFactoryWithoutMessageHandlerImplementationFactory_Fails()
        {
            // Arrange
            var services = new MessageHandlerCollection(new ServiceCollection());

            // Act / Assert
            Assert.ThrowsAny <ArgumentException>(
                () => services.WithMessageHandler <DefaultTestMessageHandler, TestMessage>(
                    messageBodySerializerImplementationFactory: serviceProvider => new TestMessageBodySerializer(),
                    messageHandlerImplementationFactory: null));
        }
Beispiel #30
0
        /// <summary>
        /// Adds a <see cref="IMessageHandler{TMessage}" /> implementation to process the messages.
        /// resources.
        /// </summary>
        /// <typeparam name="TMessageHandler">The type of the implementation.</typeparam>
        /// <typeparam name="TMessage">The type of the message that the message handler will process.</typeparam>
        /// <param name="collection">The collection of collection to use in the application.</param>
        /// <param name="implementationFactory">The function that creates the service.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="collection"/> or <paramref name="implementationFactory"/> is <c>null</c>.</exception>
        public static MessageHandlerCollection WithMessageHandler <TMessageHandler, TMessage>(
            this MessageHandlerCollection collection,
            Func <IServiceProvider, TMessageHandler> implementationFactory)
            where TMessageHandler : class, IMessageHandler <TMessage, MessageContext>
            where TMessage : class
        {
            Guard.NotNull(collection, nameof(collection), "Requires a set of collection to add the message handler");
            Guard.NotNull(implementationFactory, nameof(implementationFactory), "Requires a function to create the message handler with dependent collection");

            collection.Services.AddTransient <IMessageHandler <TMessage, MessageContext>, TMessageHandler>(implementationFactory);
            return(collection);
        }
 public void SetUp()
 {
     messageHandlerCollection = new MessageHandlerCollection();
     messageHandlerCollection.ScanAssembliesAndMapMessageHandlers(new[] { typeof(MessageHandlerCollectionTests).Assembly });
 }