public void Establish()
        {
            var messageMapperRegistry = new MessageMapperRegistry(new SimpleMessageMapperFactory(() => new MyEventMessageMapper()));

            messageMapperRegistry.Register <MyEvent, MyEventMessageMapper>();
            var policyRegistry = new PolicyRegistry
            {
                {
                    CommandProcessor.RETRYPOLICY, Policy
                    .Handle <Exception>()
                    .WaitAndRetry(new[] { TimeSpan.FromMilliseconds(50) })
                },
                {
                    CommandProcessor.CIRCUITBREAKER, Policy
                    .Handle <Exception>()
                    .CircuitBreaker(1, TimeSpan.FromMilliseconds(500))
                }
            };

            var connection = new RmqMessagingGatewayConnection
            {
                AmpqUri  = new AmqpUriSpecification(new Uri("amqp://*****:*****@localhost:5672/%2f")),
                Exchange = new Exchange("paramore.brighter.exchange")
            };

            var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(connection);
            var rmqMessageProducerFactory = new RmqMessageProducerFactory(connection);

            var connections = new List <Connection>
            {
                new Connection(
                    new ConnectionName("foo"),
                    new InputChannelFactory(rmqMessageConsumerFactory, rmqMessageProducerFactory),
                    typeof(MyEvent),
                    new ChannelName("mary"),
                    "bob",
                    timeoutInMilliseconds: 200),
                new Connection(
                    new ConnectionName("bar"),
                    new InputChannelFactory(rmqMessageConsumerFactory, rmqMessageProducerFactory),
                    typeof(MyEvent),
                    new ChannelName("alice"),
                    "simon",
                    timeoutInMilliseconds: 200)
            };

            _builder = DispatchBuilder.With()
                       .CommandProcessor(CommandProcessorBuilder.With()
                                         .Handlers(new HandlerConfiguration(new SubscriberRegistry(),
                                                                            new TinyIocHandlerFactory(new TinyIoCContainer())))
                                         .Policies(policyRegistry)
                                         .NoTaskQueues()
                                         .RequestContextFactory(new InMemoryRequestContextFactory())
                                         .Build()
                                         )
                       .MessageMappers(messageMapperRegistry)
                       .ChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory, rmqMessageProducerFactory))
                       .Connections(connections);
        }
Exemple #2
0
        public GreetingService()
        {
            log4net.Config.XmlConfigurator.Configure();

            var container = new TinyIoCContainer();

            var handlerFactory       = new TinyIocHandlerFactory(container);
            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            container.Register <IHandleRequests <GreetingCommand>, GreetingCommandHandler>();

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <GreetingCommand, GreetingCommandHandler>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry()
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(GreetingCommand), typeof(GreetingCommandMessageMapper) }
            };

            //create the gateway
            var rmqMessageConsumerFactory = new RmqMessageConsumerFactory();
            var rmqMessageProducerFactory = new RmqMessageProducerFactory();
            var builder = DispatchBuilder
                          .With()
                          .CommandProcessor(CommandProcessorBuilder.With()
                                            .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                            .Policies(policyRegistry)
                                            .NoTaskQueues()
                                            .RequestContextFactory(new InMemoryRequestContextFactory())
                                            .Build()
                                            )
                          .MessageMappers(messageMapperRegistry)
                          .ChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory, rmqMessageProducerFactory))
                          .ConnectionsFromConfiguration();

            _dispatcher = builder.Build();
        }
        public DispatchBuilderTests()
        {
            var messageMapperRegistry = new MessageMapperRegistry(new SimpleMessageMapperFactory((_) => new MyEventMessageMapper()));

            messageMapperRegistry.Register <MyEvent, MyEventMessageMapper>();

            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var rmqConnection = new RmqMessagingGatewayConnection
            {
                AmpqUri  = new AmqpUriSpecification(new Uri("amqp://*****:*****@localhost:5672/%2f")),
                Exchange = new Exchange("paramore.brighter.exchange")
            };

            var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnection);
            var container = new ServiceCollection();

            var commandProcessor = CommandProcessorBuilder.With()
                                   .Handlers(new HandlerConfiguration(new SubscriberRegistry(), (IAmAHandlerFactory) new ServiceProviderHandlerFactory(container.BuildServiceProvider())))
                                   .Policies(new PolicyRegistry
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            })
                                   .NoTaskQueues()
                                   .RequestContextFactory(new InMemoryRequestContextFactory())
                                   .Build();

            _builder = DispatchBuilder.With()
                       .CommandProcessor(commandProcessor)
                       .MessageMappers(messageMapperRegistry)
                       .DefaultChannelFactory(new ChannelFactory(rmqMessageConsumerFactory))
                       .Connections(new []
            {
                new Connection <MyEvent>(
                    new ConnectionName("foo"),
                    new ChannelName("mary"),
                    new RoutingKey("bob"),
                    timeoutInMilliseconds: 200),
                new Connection <MyEvent>(
                    new ConnectionName("bar"),
                    new ChannelName("alice"),
                    new RoutingKey("simon"),
                    timeoutInMilliseconds: 200)
            });
        }
        public void StartDispatcher(IContainer container)
        {
            var handlerFactory       = container.Resolve <IAmAHandlerFactory>();
            var messageMapperFactory = container.Resolve <IAmAMessageMapperFactory>();

            var options      = container.Resolve <IOptions <FourSettings> >();
            var authSettings = options.Value;

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <ArticoloCreated, ArticoloCreatedEventHandler>();

            subscriberRegistry.Register <ClienteCreated, ClienteCreatedEventHandler>();

            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(ArticoloCreated), typeof(ArticoloCreatedMapper) },

                { typeof(ClienteCreated), typeof(ClienteCreatedMapper) },
            };

            var handlerConfiguration = new HandlerConfiguration(subscriberRegistry, handlerFactory);

            var rmqConnnection = new RmqMessagingGatewayConnection
            {
                AmpqUri  = new AmqpUriSpecification(new Uri(authSettings.RabbitMq.Uri)),
                Exchange = new Exchange(authSettings.RabbitMq.Events, "topic")
            };

            this._commandProcessor = CommandProcessorBuilder.With()
                                     .Handlers(handlerConfiguration)
                                     .Policies(PolicyRegistry())
                                     .NoTaskQueues()
                                     .RequestContextFactory(new InMemoryRequestContextFactory())
                                     .Build();

            this._dispatcher = DispatchBuilder.With()
                               .CommandProcessor(this._commandProcessor)
                               .MessageMappers(messageMapperRegistry)
                               .DefaultChannelFactory(new InputChannelFactory(new RmqMessageConsumerFactory(rmqConnnection)))
                               .Connections(new Connection[]
            {
                new Connection <ArticoloCreated>(new ConnectionName("ArticoloCreatedEvent"),
                                                 new ChannelName("ArticoloCreated"),
                                                 new RoutingKey("ArticoloCreated"),
                                                 timeoutInMilliseconds: 200),

                new Connection <ClienteCreated>(new ConnectionName("ClienteCreatedEvent"),
                                                new ChannelName("ClienteCreated"),
                                                new RoutingKey("ClienteCreated"),
                                                timeoutInMilliseconds: 200),
            }).Build();

            this._dispatcher.Receive();
        }
Exemple #5
0
        private static void Main(string[] args)
        {
            var dispatch = new DispatchBuilder().Build();
            var cmd      = new TestCommand
            {
                Id = 23
            };
            string result = dispatch.DispatchAsync(cmd).Result;

            Console.WriteLine(result);
            Console.ReadKey();
        }
Exemple #6
0
        private static Dispatcher CreateDispatcher(
            Container container,
            List <Connection> connections, RmqMessageConsumerFactory rmqMessageConsumerFactory,
            RmqMessageProducerFactory rmqMessageProducerFactory
            )
        {
            var handlerFactoryAsync = new ServicesHandlerFactoryAsync(container);

            container.Register <IHandleRequestsAsync <BulkAddToDoCommand>, BulkAddToDoCommandHandlerAsync>();
            var messageMapperFactory = new MessageMapperFactory(container);

            container.Register <IAmAMessageMapper <BulkAddToDoCommand>, BulkAddToDoMessageMapper>();

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.RegisterAsync <BulkAddToDoCommand, BulkAddToDoCommandHandlerAsync>();

            //create policies
            var retryPolicy               = Policy.Handle <Exception>().WaitAndRetry(new[] { TimeSpan.FromMilliseconds(50), TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(150) });
            var circuitBreakerPolicy      = Policy.Handle <Exception>().CircuitBreaker(1, TimeSpan.FromMilliseconds(500));
            var retryPolicyAsync          = Policy.Handle <Exception>().WaitAndRetryAsync(new[] { TimeSpan.FromMilliseconds(50), TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(150) });
            var circuitBreakerPolicyAsync = Policy.Handle <Exception>().CircuitBreakerAsync(1, TimeSpan.FromMilliseconds(500));
            var policyRegistry            = new PolicyRegistry()
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy },
                { CommandProcessor.RETRYPOLICYASYNC, retryPolicyAsync },
                { CommandProcessor.CIRCUITBREAKERASYNC, circuitBreakerPolicyAsync }
            };

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(BulkAddToDoCommand), typeof(BulkAddToDoMessageMapper) }
            };

            var builder = DispatchBuilder
                          .With()
                          .CommandProcessor(CommandProcessorBuilder.With()
                                            .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactoryAsync))
                                            .Policies(policyRegistry)
                                            .NoTaskQueues()
                                            .RequestContextFactory(new InMemoryRequestContextFactory())
                                            .Build()
                                            )
                          .MessageMappers(messageMapperRegistry)
                          .DefaultChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory, rmqMessageProducerFactory))
                          .Connections(connections);

            var dispatcher = builder.Build();

            return(dispatcher);
        }
        public OrganizationApplicationService()
        {
            log4net.Config.XmlConfigurator.Configure();

            var container = new UnityContainer();
            var logger    = LogProvider.For <OrganizationApplicationService>();

            container.RegisterInstance(typeof(ILog), LogProvider.For <OrganizationApplicationService>(), new ContainerControlledLifetimeManager());
            container.RegisterType <AddOrganizationCommandHandler>();
            //container.RegisterType<AddEFOrganisationCommandHandler>();



            container.RegisterType <ChangeOrganizationCommandHandler>();
            container.RegisterType <OrganizationAddedEventHandler>();
            container.RegisterType <OrganizationAddedLegacyEventHandler>();

            //Factories
            //container.RegisterType(typeof(ICommandFactory<AddOrganizationCommand>),typeof(CommandFactory<AddOrganizationCommand, AxaAddOrganizationCommandExtension>));
            //container.RegisterType<IDomainFactory, AxaDomainFactory>();
            //container.RegisterType(typeof(ICommandFactory<>), typeof(CommandFactory<>));

            container.RegisterType <IDomainFactory, DomainFactory>();
            container.RegisterType(typeof(IDomainTracking <>), typeof(DomainTracking <>));

            //Repositories
            container.RegisterType <IOrganizationRepository, OrganizationRepository>();
            container.RegisterType(typeof(IEFGenericRepository <>), typeof(EFGenericRepository <>));
            container.RegisterType(typeof(IDapperGenericRepository <>), typeof(DapperGenericRepository <>));

            //container.RegisterType<DbContext, OrganisationDbContext>(new ContainerControlledLifetimeManager());
            container.RegisterType(typeof(IGenericRepository <>), typeof(EFGenericRepository <>));

            //Command Processor
            paramore.brighter.commandprocessor.CommandProcessor commandProcessor = CreateCommandProcesor(container);

            container.RegisterInstance(typeof(IAmACommandProcessor), commandProcessor);

            var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(logger);
            var rmqMessageProducerFactory = new RmqMessageProducerFactory(logger);

            var messageMapperFactory  = new UnityMessageMapperFactory(container);
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory);

            messageMapperRegistry.Register <AddOrganizationCommand, AddOrganizationCommandMessageMapper>();

            _dispatcher = DispatchBuilder.With()
                          .CommandProcessor(commandProcessor)
                          .MessageMappers(messageMapperRegistry)
                          .ChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory, rmqMessageProducerFactory))
                          .ConnectionsFromConfiguration()
                          .Build();
        }
Exemple #8
0
        static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Console(LogEventLevel.Debug)
                         .CreateLogger();

            var container = new Container();

            var builder = new ConfigurationBuilder()
                          .AddEnvironmentVariables();

            Configuration = builder.Build();


            var serviceProvider = ServiceProvider(container, out var messageMapperRegistry, out var handlerConfiguration);

            var rmqConnnection = new RmqMessagingGatewayConnection
            {
                AmpqUri  = new AmqpUriSpecification(new Uri(Configuration["RabbitMQ:Uri"])),
                Exchange = new Exchange(Configuration["RabbitMQ:Exchange"]),
            };

            var commandProcessor = CommandProcessorBuilder.With()
                                   .Handlers(handlerConfiguration)
                                   .Policies(PolicyRegistry())
                                   .NoTaskQueues()
                                   .RequestContextFactory(new InMemoryRequestContextFactory())
                                   .Build();

            var dispatcher = DispatchBuilder.With()
                             .CommandProcessor(commandProcessor)
                             .MessageMappers(messageMapperRegistry)
                             .DefaultChannelFactory(new InputChannelFactory(new RmqMessageConsumerFactory(rmqConnnection), new RmqMessageProducerFactory(rmqConnnection)))
                             .Connections(new Connection[]
            {
                new Connection <TaskCompletedEvent>(
                    new ConnectionName("TaskCompletedEvent"),
                    new ChannelName("taskcompleted.event"),
                    new RoutingKey("taskcompleted.event"),
                    timeoutInMilliseconds: 200)
            }).Build();

            dispatcher.Receive();

            Console.WriteLine("Press <Enter> to exit");
            Console.ReadLine();


            dispatcher.End().Wait();
            commandProcessor.Dispose();
            serviceProvider.Dispose();
        }
        private static Dispatcher BuildDispatcher(IServiceProvider serviceProvider)
        {
            var commandProcessor = serviceProvider.GetService <IAmACommandProcessor>();
            var options          = serviceProvider.GetService <ServiceActivatorOptions>();

            var dispatcherBuilder = DispatchBuilder.With().CommandProcessor(commandProcessor);

            var messageMapperRegistry = ServiceCollectionExtensions.MessageMapperRegistry(serviceProvider);

            return(dispatcherBuilder.MessageMappers(messageMapperRegistry)
                   .DefaultChannelFactory(options.ChannelFactory)
                   .Connections(options.Subscriptions).Build());
        }
Exemple #10
0
        private static Dispatcher BuildDispatcher()
        {
            var container      = new UnityContainer();
            var handlerFactory = new UnityHandlerFactory(container);
            // var asyncHandlerFactory = new UnityAsyncHandlerFactory(container);
            var messageMapperFactory = new UnityMessageMapperFactory(container);

            container.RegisterType <IHandleRequests <GreetingEvent>, GreetingEventHandler>();

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <GreetingEvent, GreetingEventHandler>();
            subscriberRegistry.Register <GreetingCommand, GreetingCommandHandler>();

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(GreetingEvent), typeof(GreetingEventMessageMapper) }
            };

            var connectionString       = @"Database=BrighterSqlQueue;Server=localhost;Integrated Security=SSPI;";
            var gatewayConfig          = new MsSqlMessagingGatewayConfiguration(connectionString, "QueueData");
            var messageConsumerFactory = new MsSqlMessageConsumerFactory(gatewayConfig);
            var commandProcessor       = CommandProcessorBuilder.With()
                                         .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                         .DefaultPolicy()
                                         .NoTaskQueues()
                                         .RequestContextFactory(new InMemoryRequestContextFactory())
                                         .Build();
            var dispatcher = DispatchBuilder.With()
                             .CommandProcessor(commandProcessor)
                             .MessageMappers(messageMapperRegistry)
                             .DefaultChannelFactory(new MsSqlInputChannelFactory(messageConsumerFactory))
                             .Connections(new Connection[]
            {
                new Connection <GreetingEvent>(
                    new ConnectionName("paramore.example.greeting"),
                    new ChannelName("greeting.event"),
                    new RoutingKey("greeting.event"),
                    timeoutInMilliseconds: 200)
            }
                                          ).Build();

            container.RegisterInstance <IAmACommandProcessor>(commandProcessor);
            container.RegisterType <IHandleRequests <GreetingCommand>, GreetingCommandHandler>();
            container.RegisterType <MyValidationHandler <GreetingCommand>, GreetingCommandValidationHandler>();
            container.RegisterType <MyPostAuditHandler <GreetingCommand>, GreetingCommandPostAuditHandler>();

            return(dispatcher);
        }
Exemple #11
0
        public Dispatcher Build(string hostName)
        {
            var connections = new List <Connection>();

            //TODO: Add the control bus channels.

            return(DispatchBuilder
                   .With()
                   .Logger(logger)
                   .CommandProcessor(commandProcessor)
                   .MessageMappers(new MessageMapperRegistry())
                   .ChannelFactory(channelFactory)
                   .Connections(connections)
                   .Build());
        }
        Dispatcher BuildDispatcher(HandlerConfig handlers)
        {
            var policy = BuildPolicy();
            var logger = LogProvider.GetLogger("Brighter");

            return(DispatchBuilder.With()
                   .CommandProcessor(CommandProcessorBuilder.With()
                                     .Handlers(handlers.Handlers)
                                     .Policies(policy)
                                     .NoTaskQueues()
                                     .RequestContextFactory(new InMemoryRequestContextFactory())
                                     .Build())
                   .MessageMappers(handlers.Mappers)
                   .ChannelFactory(new InputChannelFactory(new RmqMessageConsumerFactory(logger), new RmqMessageProducerFactory(logger)))
                   .ConnectionsFromConfiguration()
                   .Build());
        }
Exemple #13
0
        Dispatcher BuildDispatcher(HandlerConfig handlers)
        {
            var policy = BuildPolicy();

            //create the gateway
            var rmqConnnection = new RmqMessagingGatewayConnection
            {
                AmpqUri  = new AmqpUriSpecification(new Uri("amqp://*****:*****@localhost:5672/%2f")),
                Exchange = new Exchange("paramore.brighter.exchange"),
            };

            //<!-- Events with mapper and handler overrides -->
            //<add connectionName="Task.ReminderSent" channelName="Task.ReminderSent" routingKey="Task.ReminderSent" dataType="Tasks.Ports.Events.TaskReminderSentEvent" noOfPerformers="1" timeOutInMilliseconds="200" />

            //<!-- Generic Events -->
            //<add connectionName="Task.Added" channelName="Task.Added" routingKey="Task.Added" dataType="GenericListener.Ports.Events.GenericTaskAddedEvent" noOfPerformers="1" timeOutInMilliseconds="200" />
            //<add connectionName="Task.Edited" channelName="Task.Edited" routingKey="Task.Edited" dataType="GenericListener.Ports.Events.GenericTaskEditedEvent" noOfPerformers="1" timeOutInMilliseconds="200" />
            //<add connectionName="Task.Completed" channelName="Task.Completed" routingKey="Task.Completed" dataType="GenericListener.Ports.Events.GenericTaskCompletedEvent" noOfPerformers="1" timeOutInMilliseconds="200" />

            var inputChannelFactory = new InputChannelFactory(new RmqMessageConsumerFactory(rmqConnnection), new RmqMessageProducerFactory(rmqConnnection));

            var connections = new List <Connection>
            {
                // Events with mapper and handler overrides
                new Connection(new ConnectionName("Task.ReminderSent"), inputChannelFactory, typeof(Tasks.Ports.Events.TaskReminderSentEvent), new ChannelName("Task.ReminderSent"), "Task.ReminderSent", noOfPerformers: 1, timeoutInMilliseconds: 200),
                // Generic Events
                new Connection(new ConnectionName("Task.Added"), inputChannelFactory, typeof(GenericTaskAddedEvent), new ChannelName("Task.Added"), "Task.Added", noOfPerformers: 1, timeoutInMilliseconds: 200),
                new Connection(new ConnectionName("Task.Edited"), inputChannelFactory, typeof(GenericTaskEditedEvent), new ChannelName("Task.Edited"), "Task.Edited", noOfPerformers: 1, timeoutInMilliseconds: 200),
                new Connection(new ConnectionName("Task.Completed"), inputChannelFactory, typeof(GenericTaskCompletedEvent), new ChannelName("Task.Completed"), "Task.Completed", noOfPerformers: 1, timeoutInMilliseconds: 200),
            };

            return(DispatchBuilder.With()
                   .CommandProcessor(CommandProcessorBuilder.With()
                                     .Handlers(handlers.Handlers)
                                     .Policies(policy)
                                     .NoTaskQueues()
                                     .RequestContextFactory(new InMemoryRequestContextFactory())
                                     .Build())
                   .MessageMappers(handlers.Mappers)
                   .ChannelFactory(inputChannelFactory)
                   //.ConnectionsFromConfiguration()
                   .Connections(connections)
                   .Build());
        }
Exemple #14
0
        private static Dispatcher BuildDispatcher(IServiceProvider serviceProvider)
        {
            var commandProcessor = serviceProvider.GetService <IAmACommandProcessor>();
            var options          = serviceProvider.GetService <ServiceActivatorOptions>();

            var dispatcherBuilder = DispatchBuilder.With().CommandProcessor(commandProcessor);

            var serviceCollectionMessageMapperRegistry = serviceProvider.GetService <ServiceCollectionMessageMapperRegistry>();

            var messageMapperRegistry = new MessageMapperRegistry(new ServiceProviderMapperFactory(serviceProvider));

            foreach (var messageMapper in serviceCollectionMessageMapperRegistry)
            {
                messageMapperRegistry.Add(messageMapper.Key, messageMapper.Value);
            }

            return(dispatcherBuilder.MessageMappers(messageMapperRegistry)
                   .DefaultChannelFactory(options.ChannelFactory)
                   .Connections(options.Connections).Build());
        }
        public Dispatcher Build(string hostName)
        {
            var connections = new List <ConnectionElement>();

            /*
             * These are the control bus channels, we hardcode them because we want to know they exist, but we use
             * a base naming scheme to allow centralized management.
             */

            var configurationElement = new ConnectionElement
            {
                ChannelName    = CONFIGURATION,
                ConnectionName = CONFIGURATION,
                DataType       = typeof(ConfigurationCommand).AssemblyQualifiedName,
                RoutingKey     = hostName + "." + CONFIGURATION,
            };

            connections.Add(configurationElement);

            var heartbeatElement = new ConnectionElement
            {
                ChannelName    = HEARTBEAT,
                ConnectionName = HEARTBEAT,
                DataType       = typeof(HeartBeatCommand).AssemblyQualifiedName,
                RoutingKey     = hostName + "." + HEARTBEAT,
            };

            connections.Add(heartbeatElement);

            return(DispatchBuilder
                   .With()
                   .Logger(logger)
                   .CommandProcessor(commandProcessor)
                   .MessageMappers(new MessageMapperRegistry(new ControlBusMessageMapperFactory()))
                   .ChannelFactory(channelFactory)
                   .ConnectionsFromElements(connections)
                   .Build());
        }
Exemple #16
0
        private static Dispatcher BuildDispatcher(IServiceProvider serviceProvider)
        {
            var options = serviceProvider.GetService <ServiceActivatorOptions>();

            Func <IAmACommandProcessorProvider> providerFactory;

            if (options.UseScoped)
            {
                providerFactory = () => new ScopedCommandProcessorProvider(serviceProvider);
            }
            else
            {
                var commandProcessor = serviceProvider.GetService <IAmACommandProcessor>();
                providerFactory = () => new CommandProcessorProvider(commandProcessor);
            }

            var dispatcherBuilder = DispatchBuilder.With().CommandProcessorFactory(providerFactory);

            var messageMapperRegistry = ServiceCollectionExtensions.MessageMapperRegistry(serviceProvider);

            return(dispatcherBuilder.MessageMappers(messageMapperRegistry)
                   .DefaultChannelFactory(options.ChannelFactory)
                   .Connections(options.Subscriptions).Build());
        }
Exemple #17
0
        /// <summary>
        /// Builds this instance.
        /// </summary>
        /// <param name="hostName">Name of the host.</param>
        /// <returns>Dispatcher.</returns>
        public Dispatcher Build(string hostName)
        {
            // We want to register policies, messages and handlers for receiving built in commands. It's simple enough to do this for
            // the registries, but we cannot know your HandlerFactory implementation in order to insert. So we have to rely on
            // an internal HandlerFactory to build these for you.
            // We also need to  pass the supervised dispatcher as a dependency to our command handlers, so this allows us to manage
            // the injection of the dependency as part of our handler factory

            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry
            {
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy },
                { CommandProcessor.RETRYPOLICY, retryPolicy }
            };

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <ConfigurationCommand, ConfigurationCommandHandler>();
            subscriberRegistry.Register <HeartbeatRequest, HeartbeatRequestCommandHandler>();

            var incomingMessageMapperRegistry = new MessageMapperRegistry(new ControlBusMessageMapperFactory());

            incomingMessageMapperRegistry.Register <ConfigurationCommand, ConfigurationCommandMessageMapper>();
            incomingMessageMapperRegistry.Register <HeartbeatRequest, HeartbeatRequestCommandMessageMapper>();

            var outgoingMessageMapperRegistry = new MessageMapperRegistry(new ControlBusMessageMapperFactory());

            outgoingMessageMapperRegistry.Register <HeartbeatReply, HeartbeatReplyCommandMessageMapper>();

            var producerRegistry = _producerRegistryFactory.Create();

            var outbox = new SinkOutboxSync();

            CommandProcessor commandProcessor = null;

            commandProcessor = CommandProcessorBuilder.With()
                               .Handlers(new HandlerConfiguration(subscriberRegistry, new ControlBusHandlerFactorySync(_dispatcher, () => commandProcessor)))
                               .Policies(policyRegistry)
                               .ExternalBus(new ExternalBusConfiguration(producerRegistry, outgoingMessageMapperRegistry), outbox)
                               .RequestContextFactory(new InMemoryRequestContextFactory())
                               .Build();

            // These are the control bus channels, we hardcode them because we want to know they exist, but we use
            // a base naming scheme to allow centralized management.
            var connectionsConfiguration = new Subscription[]
            {
                new Subscription <ConfigurationCommand>(
                    new SubscriptionName($"{hostName}.{CONFIGURATION}"),
                    new ChannelName($"{hostName}.{CONFIGURATION}"),
                    new RoutingKey($"{hostName}.{CONFIGURATION}")),
                new Subscription <HeartbeatRequest>(
                    new SubscriptionName($"{hostName}.{HEARTBEAT}"),
                    new ChannelName($"{hostName}.{HEARTBEAT}"),
                    new RoutingKey($"{hostName}.{HEARTBEAT}"))
            };

            return(DispatchBuilder.With()
                   .CommandProcessorFactory(() => new CommandProcessorProvider(commandProcessor))
                   .MessageMappers(incomingMessageMapperRegistry)
                   .DefaultChannelFactory(_channelFactory)
                   .Connections(connectionsConfiguration)
                   .Build());
        }
Exemple #18
0
        private static void Main()
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Warning()
                         .WriteTo.LiterateConsole()
                         .CreateLogger();

            var container = new TinyIoCContainer();

            var handlerFactory       = new TinyIocHandlerFactory(container);
            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            container.Register <IAmACommandCounter, CommandCounter>();
            container.Register <IHandleRequests <CompetingConsumerCommand>, CompetingConsumerCommandHandler>();

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <CompetingConsumerCommand, CompetingConsumerCommandHandler>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(CompetingConsumerCommand), typeof(CompetingConsumerCommandMessageMapper) }
            };

            //create the gateway
            var messagingConfiguration =
                new MsSqlMessagingGatewayConfiguration(
                    @"Database=BrighterSqlQueue;Server=.\sqlexpress;Integrated Security=SSPI;", "QueueData");
            var messageConsumerFactory = new MsSqlMessageConsumerFactory(messagingConfiguration);

            var dispatcher = DispatchBuilder.With()
                             .CommandProcessor(CommandProcessorBuilder.With()
                                               .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                               .Policies(policyRegistry)
                                               .NoTaskQueues()
                                               .RequestContextFactory(new InMemoryRequestContextFactory())
                                               .Build())
                             .MessageMappers(messageMapperRegistry)
                             .DefaultChannelFactory(new MsSqlInputChannelFactory(messageConsumerFactory))
                             .Connections(new Connection[]
            {
                new Connection <CompetingConsumerCommand>(
                    new ConnectionName("paramore.example.multipleconsumer.command"),
                    new ChannelName("multipleconsumer.command"),
                    new RoutingKey("multipleconsumer.command"),
                    timeoutInMilliseconds: 200)
            }).Build();

            dispatcher.Receive();

            Console.WriteLine("Press Enter to stop receiving ...");
            Console.ReadLine();

            dispatcher.End().Wait();

            var count = container.Resolve <IAmACommandCounter>().Counter;


            Console.WriteLine($"There were {count} commands handled by this consumer");
            Console.WriteLine("Press Enter to exit ...");
            Console.ReadLine();
        }
        public TaskMailerService()
        {
            //Create a logger
            var properties = new NameValueCollection();

            properties["showDateTime"] = "true";
            LogManager.Adapter         = new ConsoleOutLoggerFactoryAdapter(properties);
            var logger = LogManager.GetLogger(typeof(Dispatcher));

            var container = new TinyIoCContainer();

            container.Register <IAmAMessageMapper <TaskReminderCommand>, TaskReminderCommandMessageMapper>();
            container.Register <MailTaskReminderHander, MailTaskReminderHander>();
            container.Register <IAmAMailGateway, MailGateway>();
            container.Register <ILog>(logger);
            container.Register <IAmAMailTranslator, MailTranslator>();

            var handlerFactory       = new TinyIocHandlerFactory(container);
            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <TaskReminderCommand, MailTaskReminderHander>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry()
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(TaskReminderCommand), typeof(TaskReminderCommandMessageMapper) }
            };

            //create the gateway
            var gateway = new RMQMessagingGateway(logger);

            var builder = DispatchBuilder.With()
                          .WithLogger(logger)
                          .WithCommandProcessor(CommandProcessorBuilder.With()
                                                .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                                .Policies(policyRegistry)
                                                .Logger(logger)
                                                .TaskQueues(new MessagingConfiguration(
                                                                messageStore: new RavenMessageStore(new EmbeddableDocumentStore().Initialize(), logger),
                                                                messagingGateway: gateway,
                                                                messageMapperRegistry: messageMapperRegistry
                                                                ))
                                                .RequestContextFactory(new InMemoryRequestContextFactory())
                                                .Build()
                                                )
                          .WithMessageMappers(messageMapperRegistry)
                          .WithChannelFactory(new RMQInputChannelfactory(gateway))
                          .ConnectionsFromConfiguration();

            dispatcher = builder.Build();
        }
Exemple #20
0
        public OrderService()
        {
            log4net.Config.XmlConfigurator.Configure();

            var logger = LogProvider.For <OrderService>();

            var container = new UnityContainer();

            container.RegisterInstance(typeof(ILog), LogProvider.For <OrderService>(), new ContainerControlledLifetimeManager());
            container.RegisterType <OrderUpdateCommandMessageMapper>();
            container.RegisterType <OrderUpdateCommandHandler>();
            container.RegisterType <IOrdersDAO, OrdersDAO>();
            container.RegisterType <IAmAMailGateway, MailGateway>();
            container.RegisterType <IAmAMailTranslator, MailTranslator>();

            var handlerFactory       = new UnityHandlerFactory(container);
            var messageMapperFactory = new UnityMessageMapperFactory(container);

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <OrderUpdateCommand, OrderUpdateCommandHandler>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry()
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            var commandProcessor = CommandProcessorBuilder.With()
                                   .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                   .Policies(policyRegistry)
                                   .Logger(logger)
                                   .NoTaskQueues()
                                   .RequestContextFactory(new InMemoryRequestContextFactory())
                                   .Build();

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory);

            messageMapperRegistry.Register <OrderUpdateCommand, OrderUpdateCommandMessageMapper>();

            var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(logger);

            _dispatcher = DispatchBuilder.With()
                          .Logger(logger)
                          .CommandProcessor(commandProcessor)
                          .MessageMappers(messageMapperRegistry)
                          .ChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory))
                          .ConnectionsFromConfiguration()
                          .Build();
        }
Exemple #21
0
        public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Console()
                         .CreateLogger();

            var container = new TinyIoCContainer();

            var handlerFactory       = new TinyIocHandlerFactory(container);
            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            container.Register <IHandleRequests <GreetingEvent>, GreetingEventHandler>();

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <GreetingEvent, GreetingEventHandler>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(GreetingEvent), typeof(GreetingEventMessageMapper) }
            };

            //create the gateway
            var messagingConfiguration =
                new MsSqlMessagingGatewayConfiguration(
                    @"Database=BrighterSqlQueue;Server=.\sqlexpress;Integrated Security=SSPI;", "QueueData");
            var messageConsumerFactory = new MsSqlMessageConsumerFactory(messagingConfiguration);

            var dispatcher = DispatchBuilder.With()
                             .CommandProcessor(CommandProcessorBuilder.With()
                                               .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                               .Policies(policyRegistry)
                                               .NoTaskQueues()
                                               .RequestContextFactory(new InMemoryRequestContextFactory())
                                               .Build())
                             .MessageMappers(messageMapperRegistry)
                             .DefaultChannelFactory(new ChannelFactory(messageConsumerFactory))
                             .Connections(new Connection[]
            {
                new Connection <GreetingEvent>(
                    new ConnectionName("paramore.example.greeting"),
                    new ChannelName("greeting.event"),
                    new RoutingKey("greeting.event"),
                    timeoutInMilliseconds: 200)
            }).Build();

            dispatcher.Receive();

            Console.WriteLine("Press Enter to stop ...");
            Console.ReadLine();

            dispatcher.End().Wait();
        }
        public TaskMailerService()
        {
            log4net.Config.XmlConfigurator.Configure();

            var logger = LogProvider.For <TaskMailerService>();

            var container = new TinyIoCContainer();

            container.Register <IAmAMessageMapper <TaskReminderCommand>, TaskReminderCommandMessageMapper>();
            container.Register <MailTaskReminderHander, MailTaskReminderHander>();
            container.Register <IAmAMailGateway, MailGateway>();
            container.Register <ILog>(logger);
            container.Register <IAmAMailTranslator, MailTranslator>();

            var handlerFactory       = new TinyIocHandlerFactory(container);
            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <TaskReminderCommand, MailTaskReminderHander>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry()
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            var commandProcessor = CommandProcessorBuilder.With()
                                   .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                   .Policies(policyRegistry)
                                   .Logger(logger)
                                   .NoTaskQueues()
                                   .RequestContextFactory(new InMemoryRequestContextFactory())
                                   .Build();

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(TaskReminderCommand), typeof(TaskReminderCommandMessageMapper) }
            };

            var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(logger);

            dispatcher = DispatchBuilder.With()
                         .Logger(logger)
                         .CommandProcessor(commandProcessor)
                         .MessageMappers(messageMapperRegistry)
                         .ChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory))
                         .ConnectionsFromConfiguration()
                         .Build();
        }
Exemple #23
0
        public GreetingService()
        {
            log4net.Config.XmlConfigurator.Configure(new FileInfo("log4net.config"));

            var container = new TinyIoCContainer();

            var handlerFactory       = new TinyIocHandlerFactory(container);
            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            container.Register <IHandleRequests <GreetingEvent>, GreetingEventHandler>();

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <GreetingEvent, GreetingEventHandler>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry()
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(GreetingEvent), typeof(GreetingEventMessageMapper) }
            };

            //create the gateway
            var rmqConnnection = new RmqMessagingGatewayConnection
            {
                AmpqUri  = new AmqpUriSpecification(new Uri("amqp://*****:*****@localhost:5672/%2f")),
                Exchange = new Exchange("paramore.brighter.exchange"),
            };

            var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnnection);
            var rmqMessageProducerFactory = new RmqMessageProducerFactory(rmqConnnection);


            // < add connectionName = "paramore.example.greeting" channelName = "greeting." routingKey = "greeting.command" dataType = "Greetings.Ports.Commands.GreetingEvent" timeOutInMilliseconds = "200" />
            // Service Activator connections
            var connections = new List <paramore.brighter.serviceactivator.Connection>
            {
                new paramore.brighter.serviceactivator.Connection(
                    new ConnectionName("paramore.example.greeting"),
                    new InputChannelFactory(rmqMessageConsumerFactory, rmqMessageProducerFactory),
                    typeof(GreetingEvent),
                    new ChannelName("greeting.event"),
                    "greeting.event",
                    timeoutInMilliseconds: 200)
            };

            var builder = DispatchBuilder
                          .With()
                          .CommandProcessor(CommandProcessorBuilder.With()
                                            .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                            .Policies(policyRegistry)
                                            .NoTaskQueues()
                                            .RequestContextFactory(new InMemoryRequestContextFactory())
                                            .Build()
                                            )
                          .MessageMappers(messageMapperRegistry)
                          .ChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory, rmqMessageProducerFactory))
                          .Connections(connections);

            _dispatcher = builder.Build();
        }
        public MeetingAndManagementService()
        {
            log4net.Config.XmlConfigurator.Configure();

            var container = new TinyIoCContainer();

            var handlerFactory       = new TinyIocHandlerFactory(container);
            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            container.Register <IHandleRequests <GreetingCommand>, GreetingCommandHandler>();

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <GreetingCommand, GreetingCommandHandler>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry()
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(GreetingCommand), typeof(GreetingCommandMessageMapper) }
            };

            //create the gateway
            var rmqMessageConsumerFactory = new RmqMessageConsumerFactory();
            var rmqMessageProducerFactory = new RmqMessageProducerFactory();

            var builder = DispatchBuilder
                          .With()
                          .CommandProcessor(CommandProcessorBuilder.With()
                                            .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                            .Policies(policyRegistry)
                                            .NoTaskQueues()
                                            .RequestContextFactory(new InMemoryRequestContextFactory())
                                            .Build()
                                            )
                          .MessageMappers(messageMapperRegistry)
                          .ChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory, rmqMessageProducerFactory))
                          .ConnectionsFromConfiguration();

            _dispatcher = builder.Build();

            var controlBusBuilder = ControlBusReceiverBuilder
                                    .With()
                                    .Dispatcher(_dispatcher)
                                    .ChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory, rmqMessageProducerFactory)) as ControlBusReceiverBuilder;

            _controlDispatcher = builder.Build();

            container.Register <IAmAControlBusSender>(new ControlBusSenderFactory().Create(
                                                          new MsSqlMessageStore(
                                                              new MsSqlMessageStoreConfiguration(
                                                                  "DataSource=\"" + Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase.Substring(8)), "App_Data\\MessageStore.sdf") + "\"", "Messages",
                                                                  MsSqlMessageStoreConfiguration.DatabaseType.SqlCe)
                                                              ),
                                                          new RmqMessageProducer(container.Resolve <ILog>())));
        }
        public TaskMailerService()
        {
            log4net.Config.XmlConfigurator.Configure();

            var container = new TinyIoCContainer();

            container.Register <IAmAMessageMapper <TaskReminderCommand>, Tasks.Ports.TaskReminderCommandMessageMapper>();
            container.Register <MailTaskReminderHandler, MailTaskReminderHandler>();
            container.Register <IAmAMailGateway, MailGateway>();
            container.Register <IAmAMailTranslator, MailTranslator>();

            var handlerFactory       = new TinyIocHandlerFactory(container);
            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <TaskReminderCommand, MailTaskReminderHandler>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry()
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(TaskReminderCommand), typeof(Tasks.Ports.TaskReminderCommandMessageMapper) },
                { typeof(TaskReminderSentEvent), typeof(TaskMailer.Ports.TaskReminderSentEventMapper) }
            };
            var rmqConnnection = new RmqMessagingGatewayConnection
            {
                AmpqUri  = new AmqpUriSpecification(new Uri("amqp://*****:*****@localhost:5672/%2f")),
                Exchange = new Exchange("paramore.brighter.exchange"),
            };
            var commandProcessor = CommandProcessorBuilder.With()
                                   .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                   .Policies(policyRegistry)
                                   .TaskQueues(new MessagingConfiguration(new TemporaryMessageStore(), new RmqMessageProducer(rmqConnnection), messageMapperRegistry))
                                   .RequestContextFactory(new InMemoryRequestContextFactory())
                                   .Build();

            container.Register <IAmACommandProcessor>(commandProcessor);

            var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnnection);
            var rmqMessageProducerFactory = new RmqMessageProducerFactory(rmqConnnection);
            var inputChannelFactory       = new InputChannelFactory(new RmqMessageConsumerFactory(rmqConnnection), new RmqMessageProducerFactory(rmqConnnection));

            var connections = new List <Connection>
            {
                // Events with mapper and handler overrides
                new Connection(new ConnectionName("Task.Reminder"), inputChannelFactory, typeof(TaskReminderCommand), new ChannelName("Task.Reminder"), "Task.Reminder", noOfPerformers: 1, timeoutInMilliseconds: 200),
            };

            _dispatcher = DispatchBuilder.With()
                          .CommandProcessor(commandProcessor)
                          .MessageMappers(messageMapperRegistry)
                          .ChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory, rmqMessageProducerFactory))
                          .Connections(connections)
                          .Build();
        }
Exemple #26
0
        public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.LiterateConsole()
                         .CreateLogger();

            var container = new TinyIoCContainer();

            var handlerFactory       = new TinyIocHandlerFactory(container);
            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            container.Register <IHandleRequests <GreetingEvent>, GreetingEventHandler>();

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <GreetingEvent, GreetingEventHandler>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(GreetingEvent), typeof(GreetingEventMessageMapper) }
            };

            //create the gateway
            var rmqConnnection = new RmqMessagingGatewayConnection
            {
                AmpqUri  = new AmqpUriSpecification(new Uri("amqp://*****:*****@localhost:5672/%2f")),
                Exchange = new Exchange("paramore.brighter.exchange"),
            };

            var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnnection);

            var dispatcher = DispatchBuilder.With()
                             .CommandProcessor(CommandProcessorBuilder.With()
                                               .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                               .Policies(policyRegistry)
                                               .NoTaskQueues()
                                               .RequestContextFactory(new InMemoryRequestContextFactory())
                                               .Build())
                             .MessageMappers(messageMapperRegistry)
                             .DefaultChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory))
                             .Connections(new Connection[]
            {
                new Connection <GreetingEvent>(
                    new ConnectionName("paramore.example.greeting"),
                    new ChannelName("greeting.event"),
                    new RoutingKey("greeting.event"),
                    timeoutInMilliseconds: 200)
            }).Build();

            dispatcher.Receive();

            Console.WriteLine("Press Enter to stop ...");
            Console.ReadLine();

            dispatcher.End().Wait();
        }
        /// <summary>
        /// Builds this instance.
        /// </summary>
        /// <param name="hostName">Name of the host.</param>
        /// <returns>Dispatcher.</returns>
        public Dispatcher Build(string hostName)
        {
            var connectionsConfiguration = new List <Connection>();

            /*
             * These are the control bus channels, we hardcode them because we want to know they exist, but we use
             * a base naming scheme to allow centralized management.
             */

            var connectionConfiguration = new Connection(
                new ConnectionName(hostName + "." + CONFIGURATION),
                _channelFactory,
                typeof(ConfigurationCommand),
                new ChannelName(hostName + "." + CONFIGURATION),
                hostName + "." + CONFIGURATION
                );

            //var connectionConfiguration = new ConnectionConfiguration()
            //{
            //    ChannelName = hostName  + "." + CONFIGURATION,
            //    ConnectionName = hostName  + "." + CONFIGURATION,
            //    IsDurable = true,
            //    DataType = typeof(ConfigurationCommand).FullName,
            //    RoutingKey = hostName + "." + CONFIGURATION,
            //};
            connectionsConfiguration.Add(connectionConfiguration);

            var heartbeatElement = new Connection(
                new ConnectionName(hostName + "." + HEARTBEAT),
                _channelFactory,
                typeof(HeartbeatRequest),
                new ChannelName(hostName + "." + HEARTBEAT),
                hostName + "." + HEARTBEAT,
                isDurable: false
                );

            //var heartbeatElement = new ConnectionConfiguration
            //{
            //    ChannelName = hostName  + "." + HEARTBEAT,
            //    ConnectionName = hostName  + "." + HEARTBEAT,
            //    IsDurable = false,
            //    DataType = typeof(HeartbeatRequest).FullName,
            //    RoutingKey = hostName + "." + HEARTBEAT,
            //};
            connectionsConfiguration.Add(heartbeatElement);

            /* We want to register policies, messages and handlers for receiving built in commands. It's simple enough to do this for
             * the registries, but we cannot know your HandlerFactory implementation in order to insert. So we have to rely on
             * an internal HandlerFactory to build these for you.
             *
             * We also need to  pass the supervised dispatcher as a dependency to our command handlers, so this allows us to manage
             * the injection of the dependency as part of our handler factory
             *
             */

            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry()
            {
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy },
                { CommandProcessor.RETRYPOLICY, retryPolicy }
            };


            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <ConfigurationCommand, ConfigurationCommandHandler>();
            subscriberRegistry.Register <HeartbeatRequest, HeartbeatRequestCommandHandler>();

            var incomingMessageMapperRegistry = new MessageMapperRegistry(new ControlBusMessageMapperFactory());

            incomingMessageMapperRegistry.Register <ConfigurationCommand, ConfigurationCommandMessageMapper>();
            incomingMessageMapperRegistry.Register <HeartbeatRequest, HeartbeatRequestCommandMessageMapper>();

            var outgoingMessageMapperRegistry = new MessageMapperRegistry(new ControlBusMessageMapperFactory());

            outgoingMessageMapperRegistry.Register <HeartbeatReply, HeartbeatReplyCommandMessageMapper>();

            //TODO: It doesn't feel quite right that we have to pass this in for both dispatcher channel factory and task queue configuration
            //as we should be over same broker. But, so far, refactoring either ends up exposing properties of the channel factory, which we don't want
            //or stalling on the need for channel factory to be broker defined. It is possible the fix is to drop channel factory in favour of passing
            //in producer and sender. But that's a breaking change to the builder, so contemplating for now.

            var producer = _producerFactory.Create();

            var messageStore = new SinkMessageStore();

            CommandProcessor commandProcessor = null;

            commandProcessor = CommandProcessorBuilder.With()
                               .Handlers(new HandlerConfiguration(subscriberRegistry, new ControlBusHandlerFactory(_dispatcher, () => commandProcessor)))
                               .Policies(policyRegistry: policyRegistry)
                               .TaskQueues(new MessagingConfiguration(messageStore, producer, outgoingMessageMapperRegistry))
                               .RequestContextFactory(new InMemoryRequestContextFactory())
                               .Build();

            return(DispatchBuilder
                   .With()
                   .CommandProcessor(commandProcessor)
                   .MessageMappers(incomingMessageMapperRegistry)
                   .ChannelFactory(_channelFactory)
                   .Connections(connectionsConfiguration)
                   .Build());
        }
Exemple #28
0
        public PersonService()
        {
            log4net.Config.XmlConfigurator.Configure();

            //injecao de dependencia
            var container      = new TinyIoCContainer();
            var handlerFactory = new TinyIocHandlerFactory(container);

            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            container.Register <IHandleRequests <EventoPersonalisado>, PersonEventHandler>();

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <EventoPersonalisado, PersonEventHandler>();

            //create policies
            var retryPolicy = Policy.Handle <Exception>().WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50), TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy.Handle <Exception>().CircuitBreaker(1, TimeSpan.FromMilliseconds(500));
            var policyRegistry       = new PolicyRegistry
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            //mapeando objetos
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(EventoPersonalisado), typeof(PersonEventMessageMapper) }
            };

            //gateway de conexao
            var rmqConnnection = new RmqMessagingGatewayConnection
            {
                AmpqUri  = new AmqpUriSpecification(new Uri("amqp://*****:*****@localhost:5672/%2f")),
                Exchange = new Exchange("paramore.brighter.exchange"),
            };

            var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnnection);

            _dispatcher = DispatchBuilder.With()
                          .CommandProcessor(CommandProcessorBuilder.With()
                                            .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                            .Policies(policyRegistry)
                                            .NoTaskQueues()
                                            .RequestContextFactory(new InMemoryRequestContextFactory())
                                            .Build())
                          .MessageMappers(messageMapperRegistry)
                          .DefaultChannelFactory(new ChannelFactory(rmqMessageConsumerFactory))
                          .Connections(new[]
            {
                new Connection <EventoPersonalisado>(
                    new ConnectionName("paramore.example.Person"),
                    new ChannelName("order"),
                    new RoutingKey("order"),
                    timeoutInMilliseconds: 200)
            }).Build();
        }
Exemple #29
0
        /// <summary>
        /// Builds this instance.
        /// </summary>
        /// <param name="hostName">Name of the host.</param>
        /// <returns>Dispatcher.</returns>
        public Dispatcher Build(string hostName)
        {
            // We want to register policies, messages and handlers for receiving built in commands. It's simple enough to do this for
            // the registries, but we cannot know your HandlerFactory implementation in order to insert. So we have to rely on
            // an internal HandlerFactory to build these for you.
            // We also need to  pass the supervised dispatcher as a dependency to our command handlers, so this allows us to manage
            // the injection of the dependency as part of our handler factory

            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry
            {
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy },
                { CommandProcessor.RETRYPOLICY, retryPolicy }
            };

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <ConfigurationCommand, ConfigurationCommandHandler>();
            subscriberRegistry.Register <HeartbeatRequest, HeartbeatRequestCommandHandler>();

            var incomingMessageMapperRegistry = new MessageMapperRegistry(new ControlBusMessageMapperFactory());

            incomingMessageMapperRegistry.Register <ConfigurationCommand, ConfigurationCommandMessageMapper>();
            incomingMessageMapperRegistry.Register <HeartbeatRequest, HeartbeatRequestCommandMessageMapper>();

            var outgoingMessageMapperRegistry = new MessageMapperRegistry(new ControlBusMessageMapperFactory());

            outgoingMessageMapperRegistry.Register <HeartbeatReply, HeartbeatReplyCommandMessageMapper>();

            //TODO: It doesn't feel quite right that we have to pass this in for both dispatcher channel factory and task queue configuration
            //as we should be over same broker. But, so far, refactoring either ends up exposing properties of the channel factory, which we don't want
            //or stalling on the need for channel factory to be broker defined. It is possible the fix is to drop channel factory in favour of passing
            //in producer and sender. But that's a breaking change to the builder, so contemplating for now.

            var producer = _producerFactory.Create();

            var outbox = new SinkOutbox();

            CommandProcessor commandProcessor = null;

            commandProcessor = CommandProcessorBuilder.With()
                               .Handlers(new HandlerConfiguration(subscriberRegistry, new ControlBusHandlerFactory(_dispatcher, () => commandProcessor)))
                               .Policies(policyRegistry)
                               .TaskQueues(new MessagingConfiguration(producer, outgoingMessageMapperRegistry), outbox)
                               .RequestContextFactory(new InMemoryRequestContextFactory())
                               .Build();

            // These are the control bus channels, we hardcode them because we want to know they exist, but we use
            // a base naming scheme to allow centralized management.
            var connectionsConfiguration = new Subscription[]
            {
                new Subscription <ConfigurationCommand>(
                    new SubscriptionName($"{hostName}.{CONFIGURATION}"),
                    new ChannelName($"{hostName}.{CONFIGURATION}"),
                    new RoutingKey($"{hostName}.{CONFIGURATION}")),
                new Subscription <HeartbeatRequest>(
                    new SubscriptionName($"{hostName}.{HEARTBEAT}"),
                    new ChannelName($"{hostName}.{HEARTBEAT}"),
                    new RoutingKey($"{hostName}.{HEARTBEAT}"))
            };

            return(DispatchBuilder.With()
                   .CommandProcessor(commandProcessor)
                   .MessageMappers(incomingMessageMapperRegistry)
                   .DefaultChannelFactory(_channelFactory)
                   .Connections(connectionsConfiguration)
                   .Build());
        }
Exemple #30
0
        public ManagementAndMonitoringService()
        {
            log4net.Config.XmlConfigurator.Configure();

            var container = new TinyIoCContainer();

            var handlerFactory       = new TinyIocHandlerFactory(container);
            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            container.Register <IHandleRequests <GreetingCommand>, GreetingCommandHandler>();

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <GreetingCommand, GreetingCommandHandler>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry()
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(GreetingCommand), typeof(GreetingCommandMessageMapper) }
            };

            var rmqGatewayMessages = new RmqMessagingGatewayConnection
            {
                AmpqUri  = new AmqpUriSpecification(new Uri("amqp://*****:*****@localhost:5672/%2f")),
                Exchange = new Exchange("paramore.brighter.exchange"),
            };
            var rmqGatewayMonitoring = new RmqMessagingGatewayConnection
            {
                AmpqUri  = new AmqpUriSpecification(new Uri("amqp://*****:*****@localhost:5672/%2f")),
                Exchange = new Exchange("paramore.brighter.exchange"),
            };

            //create the gateway
            var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqGatewayMessages);
            var rmqMessageProducerFactory = new RmqMessageProducerFactory(rmqGatewayMessages);

            var connections = new List <Connection>
            {
            };

            var builder = DispatchBuilder
                          .With()
                          .CommandProcessor(CommandProcessorBuilder.With()
                                            .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                            .Policies(policyRegistry)
                                            .NoTaskQueues()
                                            .RequestContextFactory(new InMemoryRequestContextFactory())
                                            .Build()
                                            )
                          .MessageMappers(messageMapperRegistry)
                          .DefaultChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory))
                          .Connections(connections);

            _dispatcher = builder.Build();

            var controlBusBuilder = ControlBusReceiverBuilder
                                    .With()
                                    .Dispatcher(_dispatcher)
                                    .ProducerFactory(rmqMessageProducerFactory)
                                    .ChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory)) as ControlBusReceiverBuilder;

            _controlDispatcher = controlBusBuilder.Build(Environment.MachineName + "." + "ManagementAndMonitoring");

            container.Register <IAmAControlBusSender>(new ControlBusSenderFactory().Create(
                                                          new SqliteMessageStore(
                                                              new SqliteMessageStoreConfiguration(
                                                                  "DataSource=\"" + Path.Combine(Path.GetDirectoryName(typeof(GreetingCommand).GetTypeInfo().Assembly.CodeBase.Substring(8)), "App_Data\\MessageStore.sdf") + "\"", "Messages")
                                                              ),
                                                          new RmqMessageProducer(rmqGatewayMonitoring)));
        }