static void Main(string[] args) { var properties = new NameValueCollection(); properties["showDateTime"] = "true"; LogManager.Adapter = new ConsoleOutLoggerFactoryAdapter(properties); var logger = LogManager.GetLogger(typeof (Program)); var registry = new SubscriberRegistry(); registry.Register<GreetingCommand, GreetingCommandHandler>(); var builder = CommandProcessorBuilder.With() .Handlers(new HandlerConfiguration( subscriberRegistry: registry, handlerFactory: new SimpleHandlerFactory(logger) )) .NoPolicy() .Logger(logger) .NoTaskQueues() .RequestContextFactory(new InMemoryRequestContextFactory()); var commandProcessor = builder.Build(); commandProcessor.Send(new GreetingCommand("Ian")); }
protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); var logger = LogProvider.GetLogger(this.GetType().Namespace); container.Register(logger); var subscriberRegistry = new SubscriberRegistry(); subscriberRegistry.Register<AddTaskCommand, AddTaskCommandHandler>(); subscriberRegistry.Register<CompleteTaskCommand, CompleteTaskCommandHandler>(); container.Register<IHandleRequests<AddTaskCommand>, AddTaskCommandHandler>().AsMultiInstance(); container.Register<IHandleRequests<CompleteTaskCommand>, CompleteTaskCommandHandler>().AsMultiInstance(); var handlerFactory = new TinyIoCHandlerFactory(container); 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 sqlMessageStore = new MsSqlMessageStore(new MsSqlMessageStoreConfiguration("Server=.;Database=brighterMessageStore;Trusted_Connection=True", "messages", MsSqlMessageStoreConfiguration.DatabaseType.MsSqlServer), logger); var gateway = new AzureServiceBusMessageProducer(logger); container.Register<IAmAMessageMapper<TaskReminderCommand>, TaskReminderCommandMessageMapper>().AsMultiInstance(); var messageMapperFactory = new TinyIoCMessageMapperFactory(container); var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory); messageMapperRegistry.Add(typeof(TaskReminderCommand), typeof(TaskReminderCommandMessageMapper)); var commandProcessor = CommandProcessorBuilder .With() .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory)) .Policies(policyRegistry) .TaskQueues(new MessagingConfiguration(sqlMessageStore, gateway, messageMapperRegistry)) .RequestContextFactory(new InMemoryRequestContextFactory()) .Build(); container.Register<IAmACommandProcessor>(commandProcessor); }
static void Main(string[] args) { FulfillmentDB.Initialize(); FulfillmentDB context = new FulfillmentDB(); var product = EnsureProduct(context); EnsureWarehouse(context, product); Console.WriteLine("Starting order processor..."); SubscriberRegistry<OrderShipped> subscrptionRegistry = new SubscriberRegistry<OrderShipped>(); MessageProcessor<PlaceOrder> orderProcessor = new MessageProcessor<PlaceOrder>( typeof(PlaceOrder).FullName, () => new PlaceOrderHandler(subscrptionRegistry)); orderProcessor.Start(); MessageProcessor<Subscription> subscriptionProcessor = new MessageProcessor<Subscription>( typeof(OrderShipped).FullName, () => new SubscriptionHandler<OrderShipped>( subscrptionRegistry)); subscriptionProcessor.Start(); Console.ReadKey(); orderProcessor.Stop(); subscriptionProcessor.Stop(); }
public static void Run(UnityContainer container) { container.RegisterType<StoreFrontController>(); container.RegisterInstance(typeof(ILog), LogProvider.For<StoreService>(), new ContainerControlledLifetimeManager()); container.RegisterType<AddOrderCommandHandler>(); container.RegisterType<AddProductCommandHandler>(); container.RegisterType<ChangeProductCommandHandler>(); container.RegisterType<RemoveProductCommandHandler>(); container.RegisterType<IProductsDAO, ProductsDAO>(); var logger = container.Resolve<ILog>(); var handlerFactory = new UnityHandlerFactory(container); var subscriberRegistry = new SubscriberRegistry(); subscriberRegistry.Register<AddOrderCommand, AddOrderCommandHandler>(); subscriberRegistry.Register<AddProductCommand, AddProductCommandHandler>(); subscriberRegistry.Register<ChangeProductCommand, ChangeProductCommandHandler>(); subscriberRegistry.Register<RemoveProductCommand, RemoveProductCommandHandler>(); //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 messageMapperFactory = new UnityMessageMapperFactory(container); var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory); messageMapperRegistry.Register<AddOrderCommand, AddOrderCommandMessageMapper>(); var gateway = new RmqMessageProducer(container.Resolve<ILog>()); var dbPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase.Substring(8)), "App_Data\\MessageStore.sdf"); IAmAMessageStore<Message> sqlMessageStore = new MsSqlMessageStore(new MsSqlMessageStoreConfiguration("DataSource=\"" + dbPath + "\"", "Messages", MsSqlMessageStoreConfiguration.DatabaseType.SqlCe), logger); var commandProcessor = CommandProcessorBuilder.With() .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory)) .Policies(policyRegistry) .Logger(logger) .TaskQueues(new MessagingConfiguration(sqlMessageStore, gateway, messageMapperRegistry)) .RequestContextFactory(new InMemoryRequestContextFactory()) .Build(); container.RegisterInstance(typeof(IAmACommandProcessor), commandProcessor); }
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 static void Run(UnityContainer container) { container.RegisterType<FeedController>(); container.RegisterType<ProductsController>(); container.RegisterInstance(typeof(ILog), LogProvider.For<ProductService>(), new ContainerControlledLifetimeManager()); container.RegisterType<IProductsDAO, ProductsDAO>(); container.RegisterType<AddProductCommandHandler>(); container.RegisterType<ChangeProductCommandHandler>(); container.RegisterType<ProductAddedEventHandler>(); container.RegisterType<ProductChangedEventHandler>(); container.RegisterType<ProductRemovedEventHandler>(); container.RegisterType<RemoveProductCommandHandler>(); var handlerFactory = new UnityHandlerFactory(container); var subscriberRegistry = new SubscriberRegistry { {typeof(AddProductCommand), typeof(AddProductCommandHandler)}, {typeof(ChangeProductCommand), typeof(ChangeProductCommandHandler)}, {typeof(RemoveProductCommand), typeof(RemoveProductCommandHandler)}, {typeof(ProductAddedEvent), typeof(ProductAddedEventHandler)}, {typeof(ProductRemovedEvent), typeof(ProductRemovedEventHandler)}, }; //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(container.Resolve<ILog>()) .NoTaskQueues() .RequestContextFactory(new InMemoryRequestContextFactory()) .Build(); container.RegisterInstance(typeof(IAmACommandProcessor), commandProcessor); }
public StoreService() { log4net.Config.XmlConfigurator.Configure(); var logger = LogProvider.For<StoreService>(); var container = new UnityContainer(); container.RegisterInstance(typeof(ILog), LogProvider.For<StoreService>(), new ContainerControlledLifetimeManager()); container.RegisterType<IProductsDAO, ProductsDAO>(); container.RegisterType<ILastReadFeedItemDAO, LastReadFeedItemDAO>(); container.RegisterType<AddProductCommandHandler>(); container.RegisterType<ChangeProductCommandHandler>(); container.RegisterType<RemoveProductCommandHandler>(); var handlerFactory = new UnityHandlerFactory(container); var subscriberRegistry = new SubscriberRegistry { {typeof(AddProductCommand), typeof(AddProductCommandHandler)}, {typeof(ChangeProductCommand), typeof(ChangeProductCommandHandler)}, {typeof(RemoveProductCommand), typeof(RemoveProductCommandHandler)}, }; //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(); _consumer = new Consumer(new LastReadFeedItemDAO(), commandProcessor, logger); }
public CommandProcessorWithNullFeatureSwitchConfig() { _registry = new SubscriberRegistry(); _registry.Register <MyCommand, MyFeatureSwitchedConfigHandler>(); var container = new ServiceCollection(); container.AddSingleton <MyFeatureSwitchedConfigHandler>(); container.AddTransient <FeatureSwitchHandler <MyCommand> >(); container.AddSingleton <IBrighterOptions>(new BrighterOptions() { HandlerLifetime = ServiceLifetime.Transient }); _provider = container.BuildServiceProvider(); _handlerFactory = new ServiceProviderHandlerFactory(_provider); }
public void Setup() { var logger = new Mock <ILog>().Object; var registry = new SubscriberRegistry(); registry.Register <TestCommand, TestUnusedCommandHandler>(); var container = new TinyIoCContainer(); var handlerFactory = new TinyIoCHandlerFactory(container); container.Register <IHandleRequests <TestCommand>, TestUnusedCommandHandler>(); container.Register <IHandleRequests <TestCommand>, TestAbortingHandler <TestCommand> >(); container.Register(logger); commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), logger); }
public void Establish() { var registry = new SubscriberRegistry(); registry.Register <MyEvent, MyEventHandler>(); registry.Register <MyEvent, MyOtherEventHandler>(); registry.Register <MyEvent, MyThrowingEventHandler>(); var container = new TinyIoCContainer(); var handlerFactory = new TinyIocHandlerFactory(container); container.Register <IHandleRequests <MyEvent>, MyEventHandler>("MyEventHandler"); container.Register <IHandleRequests <MyEvent>, MyOtherEventHandler>("MyOtherHandler"); container.Register <IHandleRequests <MyEvent>, MyThrowingEventHandler>("MyThrowingHandler"); _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry()); }
public CommandProcessorSendWithMultipleMatchesAsyncTests() { var registry = new SubscriberRegistry(); registry.RegisterAsync <MyCommand, MyCommandHandlerAsync>(); registry.RegisterAsync <MyCommand, MyImplicitHandlerAsync>(); var container = new TinyIoCContainer(); var handlerFactory = new TinyIocHandlerFactoryAsync(container); container.Register <IHandleRequestsAsync <MyCommand>, MyCommandHandlerAsync>(); container.Register <IHandleRequestsAsync <MyCommand>, MyImplicitHandlerAsync>(); container.Register <IHandleRequestsAsync <MyCommand>, MyLoggingHandlerAsync <MyCommand> >(); container.Register(_receivedMessages); _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry()); }
public PipelineBuilderAsyncTests() { var registry = new SubscriberRegistry(); registry.RegisterAsync <MyCommand, MyImplicitHandlerAsync>(); var container = new ServiceCollection(); container.AddTransient <MyImplicitHandlerAsync>(); container.AddTransient <MyLoggingHandlerAsync <MyCommand> >(); var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); _pipelineBuilder = new PipelineBuilder <MyCommand>(registry, (IAmAHandlerFactoryAsync)handlerFactory); PipelineBuilder <MyCommand> .ClearPipelineCache(); }
public PipelineForeignAttributesTests() { var registry = new SubscriberRegistry(); registry.Register <MyCommand, MyObsoleteCommandHandler>(); var container = new ServiceCollection(); container.AddTransient <MyObsoleteCommandHandler>(); container.AddTransient <MyValidationHandler <MyCommand> >(); container.AddTransient <MyLoggingHandler <MyCommand> >(); var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); _pipelineBuilder = new PipelineBuilder <MyCommand>(registry, (IAmAHandlerFactory)handlerFactory); PipelineBuilder <MyCommand> .ClearPipelineCache(); }
public CommandProcessorMissingPolicyFromRegistryTests() { var registry = new SubscriberRegistry(); registry.Register <MyCommand, MyDoesNotFailPolicyHandler>(); var container = new ServiceCollection(); container.AddTransient <MyDoesNotFailPolicyHandler>(); container.AddTransient <ExceptionPolicyHandler <MyCommand> >(); var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); MyDoesNotFailPolicyHandler.ReceivedCommand = false; _commandProcessor = new CommandProcessor(registry, (IAmAHandlerFactory)handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry()); }
public TimeoutHandlerFailsCheckTests() { var registry = new SubscriberRegistry(); registry.Register <MyCommand, MyFailsDueToTimeoutHandler>(); var container = new TinyIoCContainer(); var handlerFactory = new TinyIocHandlerFactory(container); container.Register <IHandleRequests <MyCommand>, MyFailsDueToTimeoutHandler>().AsSingleton(); container.Register <IHandleRequests <MyCommand>, TimeoutPolicyHandler <MyCommand> >().AsSingleton(); MyFailsDueToTimeoutHandlerStateTracker.WasCancelled = false; MyFailsDueToTimeoutHandlerStateTracker.TaskCompleted = true; _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry()); }
public void Establish() { var registry = new SubscriberRegistry(); registry.Register <MyCommand, MyFailsWithFallbackMultipleHandlers>(); var policyRegistry = new PolicyRegistry(); var container = new TinyIoCContainer(); var handlerFactory = new TinyIocHandlerFactory(container); container.Register <IHandleRequests <MyCommand>, MyFailsWithFallbackMultipleHandlers>().AsSingleton(); container.Register <IHandleRequests <MyCommand>, FallbackPolicyHandler <MyCommand> >().AsSingleton(); MyFailsWithFallbackMultipleHandlers.ReceivedCommand = false; _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), policyRegistry); }
public CommandProcessorPublishMultipleMatchesAsyncTests() { var registry = new SubscriberRegistry(); registry.RegisterAsync <MyEvent, MyEventHandlerAsync>(); registry.RegisterAsync <MyEvent, MyOtherEventHandlerAsync>(); var container = new TinyIoCContainer(); var handlerFactory = new TinyIocHandlerFactoryAsync(container); container.Register <IHandleRequestsAsync <MyEvent>, MyEventHandlerAsync>(); container.Register <IHandleRequestsAsync <MyEvent>, MyOtherEventHandlerAsync>(); container.Register(_receivedMessages); _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry()); PipelineBuilder <MyEvent> .ClearPipelineCache(); }
public FallbackHandlerOnExceptionTests() { var registry = new SubscriberRegistry(); registry.Register <MyCommand, MyFailsWithFallbackDivideByZeroHandler>(); var policyRegistry = new PolicyRegistry(); var container = new TinyIoCContainer(); var handlerFactory = new TinyIocHandlerFactory(container); container.Register <IHandleRequests <MyCommand>, MyFailsWithFallbackDivideByZeroHandler>().AsSingleton(); container.Register <IHandleRequests <MyCommand>, FallbackPolicyHandler <MyCommand> >().AsSingleton(); MyFailsWithFallbackDivideByZeroHandler.ReceivedCommand = false; _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), policyRegistry); }
public void When_discovering_commands_using_reflection_callback_is_invoked_with_discovered_mapping() { var subscriberRegistry = new SubscriberRegistry(); var discoveredHandlers = new [] { typeof(ADiscoveredHandlerThatUsesTheBaseImplementation) }; SubscriberRegistryExtensions.DiscoveredPair callbackPair = null; subscriberRegistry.RegisterCommandHandlers(discoveredHandlers, onDiscovery: pair => { callbackPair = pair; }); callbackPair.Command.ShouldBeEquivalentTo(typeof(ADiscoveredHandlerThatUsesTheBaseImplementationCommand)); callbackPair.CommandHandler.ShouldBeEquivalentTo(typeof(ADiscoveredHandlerThatUsesTheBaseImplementation)); subscriberRegistry.ToList()[0].Key.ShouldBeEquivalentTo(typeof(ADiscoveredHandlerThatUsesTheBaseImplementationCommand)); subscriberRegistry.ToList()[0].Value[0].ShouldBeEquivalentTo(typeof(ADiscoveredHandlerThatUsesTheBaseImplementation)); }
public CommandProcessorPipelineStepsTests() { var registry = new SubscriberRegistry(); registry.Register <MyCommand, MyStepsPreAndPostDecoratedHandler>(); var container = new ServiceCollection(); container.AddTransient <MyStepsPreAndPostDecoratedHandler>(); container.AddTransient <MyStepsValidationHandler <MyCommand> >(); container.AddTransient <MyStepsLoggingHandler <MyCommand> >(); var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); _commandProcessor = new CommandProcessor(registry, (IAmAHandlerFactory)handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry()); PipelineBuilder <MyCommand> .ClearPipelineCache(); }
private CommandProcessor CommandProcessorRegistrar(TinyIoCContainer container, ILog logger) { //Database dao container.Register <ITasksDAO, TasksDAO>().AsSingleton(); //create handler var handlerFactory = new TinyIocHandlerFactory(container); var subscriberRegistry = new SubscriberRegistry(); container.Register <IHandleRequests <AddTaskCommand>, AddTaskCommandHandler>().AsMultiInstance(); subscriberRegistry.Register <AddTaskCommand, AddTaskCommandHandler>(); //complete handler container.Register <IHandleRequests <CompleteTaskCommand>, CompleteTaskCommandHandler>().AsMultiInstance(); subscriberRegistry.Register <CompleteTaskCommand, CompleteTaskCommandHandler>(); //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 container.Register <IAmAMessageMapper <TaskReminderCommand>, TaskReminderCommandMessageMapper>().AsMultiInstance(); var messageMapperFactory = new TinyIoCMessageMapperFactory(container); var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory); messageMapperRegistry.Add(typeof(TaskReminderCommand), typeof(TaskReminderCommandMessageMapper)); var ravenMessageStore = new RavenMessageStore(new EmbeddableDocumentStore().Initialize(), logger); var gateway = new RmqMessageProducer(logger); var commandProcessor = CommandProcessorBuilder.With() .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory)) .Policies(policyRegistry) .Logger(logger) .TaskQueues(new MessagingConfiguration(ravenMessageStore, gateway, messageMapperRegistry)) .RequestContextFactory(new InMemoryRequestContextFactory()) .Build(); return(commandProcessor); }
private CommandProcessor CommandProcessorRegistrar(TinyIoCContainer container) { //Database dao container.Register<ITasksDAO, TasksDAO>().AsSingleton(); //create handler var handlerFactory = new TinyIocHandlerFactory(container); var subscriberRegistry = new SubscriberRegistry(); container.Register<IHandleRequests<AddTaskCommand>, AddTaskCommandHandler>().AsMultiInstance(); subscriberRegistry.Register<AddTaskCommand, AddTaskCommandHandler>(); //complete handler container.Register<IHandleRequests<CompleteTaskCommand>, CompleteTaskCommandHandler>().AsMultiInstance(); subscriberRegistry.Register<CompleteTaskCommand, CompleteTaskCommandHandler>(); //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 container.Register<IAmAMessageMapper<TaskReminderCommand>, TaskReminderCommandMessageMapper>().AsMultiInstance(); var messageMapperFactory = new TinyIoCMessageMapperFactory(container); var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory); messageMapperRegistry.Add(typeof(TaskReminderCommand), typeof(TaskReminderCommandMessageMapper)); messageMapperRegistry.Add(typeof(TaskAddedEvent), typeof(TaskAddedEventMapper)); messageMapperRegistry.Add(typeof(TaskEditedEvent), typeof(TaskEditedEventMapper)); messageMapperRegistry.Add(typeof(TaskCompletedEvent), typeof(TaskCompletedEventMapper)); messageMapperRegistry.Add(typeof(TaskReminderSentEvent), typeof(TaskReminderSentEventMapper)); var gateway = new RmqMessageProducer(); IAmAMessageStore<Message> sqlMessageStore = new MsSqlMessageStore(new MsSqlMessageStoreConfiguration("Server=.;Database=brighterMessageStore;Trusted_Connection=True", "messages", MsSqlMessageStoreConfiguration.DatabaseType.MsSqlServer)); var commandProcessor = CommandProcessorBuilder.With() .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory)) .Policies(policyRegistry) .TaskQueues(new MessagingConfiguration(sqlMessageStore, gateway, messageMapperRegistry)) .RequestContextFactory(new InMemoryRequestContextFactory()) .Build(); container.Register<IAmACommandProcessor>(commandProcessor); return commandProcessor; }
public void Setup() { var logger = new Mock <ILog>().Object; var registry = new SubscriberRegistry(); registry.Register <TestEvent, TestEventHandler>(); registry.Register <TestEvent, TestOtherEventHandler>(); var container = new TinyIoCContainer(); var handlerFactory = new TinyIoCHandlerFactory(container); container.Register <IHandleRequests <TestEvent>, TestEventHandler>("TestEventHandler"); container.Register <IHandleRequests <TestEvent>, TestOtherEventHandler>("TestOtherHandler"); container.Register(logger); commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), logger); }
public CommandProcessorPublishMultipleMatchesTests() { var registry = new SubscriberRegistry(); registry.Register <MyEvent, MyEventHandler>(); registry.Register <MyEvent, MyOtherEventHandler>(); var container = new ServiceCollection(); container.AddTransient <MyEventHandler>(); container.AddTransient <MyOtherEventHandler>(); container.AddSingleton(_receivedMessages); var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); _commandProcessor = new CommandProcessor(registry, (IAmAHandlerFactory)handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry()); PipelineBuilder <MyEvent> .ClearPipelineCache(); }
public PublishingToMultipleSubscribersTests() { var registry = new SubscriberRegistry(); registry.Register <MyEvent, MyEventHandler>(); registry.Register <MyEvent, MyOtherEventHandler>(); registry.Register <MyEvent, MyThrowingEventHandler>(); var container = new TinyIoCContainer(); var handlerFactory = new TinyIocHandlerFactory(container); container.Register <IHandleRequests <MyEvent>, MyEventHandler>(); container.Register <IHandleRequests <MyEvent>, MyOtherEventHandler>(); container.Register <IHandleRequests <MyEvent>, MyThrowingEventHandler>(); container.Register(_receivedMessages); _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry()); }
public FallbackHandlerOnExceptionTests() { var registry = new SubscriberRegistry(); registry.Register <MyCommand, MyFailsWithFallbackDivideByZeroHandler>(); var policyRegistry = new PolicyRegistry(); var container = new ServiceCollection(); container.AddSingleton <MyFailsWithFallbackDivideByZeroHandler>(); container.AddSingleton <FallbackPolicyHandler <MyCommand> >(); var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); MyFailsWithFallbackDivideByZeroHandler.ReceivedCommand = false; _commandProcessor = new CommandProcessor(registry, (IAmAHandlerFactory)handlerFactory, new InMemoryRequestContextFactory(), policyRegistry); }
private void GetSubscriberRegistry() { if (this.registry == null) { this.InitialiseContainer(); var blob = this.container.GetBlockBlobReference("registry.json"); if (blob.ExistsAsync().Result) { var json = blob.DownloadTextAsync().Result; var results = JsonConvert.DeserializeObject(json, typeof(SubscriberRegistry)); this.registry = (SubscriberRegistry)results; } else { this.registry = new SubscriberRegistry(); } } }
public static ISubscriberRegistry Configure(params Assembly[] assembies) { var registry = new SubscriberRegistry(); var methods = assembies.SelectMany(a => a.GetTypes()) .SelectMany(t => t.GetMethods()) .Where(m => m.GetCustomAttributes(typeof(EventListenerAttribute), false).Length > 0) .ToArray(); foreach (var method in methods) { var attribute = method.GetCustomAttribute <EventListenerAttribute>(); registry.Register(attribute, method); } return(registry); }
public CommandProcessorBuildDefaultInboxPublishAsyncTests() { var handler = new MyEventHandlerAsync(new Dictionary <string, Guid>()); var subscriberRegistry = new SubscriberRegistry(); //This handler has no Inbox attribute subscriberRegistry.RegisterAsync <MyEvent, MyEventHandlerAsync>(); var container = new ServiceCollection(); container.AddSingleton <MyEventHandlerAsync>(handler); container.AddSingleton <IAmAnInboxAsync>(_inbox); container.AddTransient <UseInboxHandlerAsync <MyEvent> >(); var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); var retryPolicy = Policy .Handle <Exception>() .RetryAsync(); var circuitBreakerPolicy = Policy .Handle <Exception>() .CircuitBreakerAsync(1, TimeSpan.FromMilliseconds(1)); var inboxConfiguration = new InboxConfiguration( InboxScope.All, //grab all the events onceOnly: true, //only allow once actionOnExists: OnceOnlyAction.Throw //throw on duplicates (we should be the only entry after) ); _commandProcessor = new CommandProcessor( subscriberRegistry, (IAmAHandlerFactoryAsync)handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry { { CommandProcessor.RETRYPOLICYASYNC, retryPolicy }, { CommandProcessor.CIRCUITBREAKERASYNC, circuitBreakerPolicy } }, inboxConfiguration: inboxConfiguration ); }
private static paramore.brighter.commandprocessor.CommandProcessor CreateCommandProcesor(UnityContainer container) { var logger = container.Resolve <ILog>(); var handlerFactory = new UnityHandlerFactory(container); var subscriberRegistry = new SubscriberRegistry(); subscriberRegistry.Register <AddOrganizationCommand, AddOrganizationCommandHandler>(); //subscriberRegistry.Register<AddOrganizationCommand, AddEFOrganisationCommandHandler>(); subscriberRegistry.Register <ChangeOrganizationCommand, ChangeOrganizationCommandHandler>(); subscriberRegistry.Register <OrganizationAddedEvent, OrganizationAddedEventHandler>(); subscriberRegistry.Register <OrganizationAddedEvent, OrganizationAddedLegacyEventHandler>(); //create retry policies var retryPolicy = Policy .Handle <Exception>() .WaitAndRetry(new[] { TimeSpan.FromMilliseconds(50), TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(150) }); //create circuit breaker policies var circuitBreakerPolicy = Policy .Handle <Exception>() .CircuitBreaker(1, TimeSpan.FromMilliseconds(500)); var policyRegistry = new PolicyRegistry() { { paramore.brighter.commandprocessor.CommandProcessor.RETRYPOLICY, retryPolicy }, { paramore.brighter.commandprocessor.CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy } }; var commandProcessor = CommandProcessorBuilder.With() .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory)) .Policies(policyRegistry) .NoTaskQueues() .RequestContextFactory(new InMemoryRequestContextFactory()) .Build(); return(commandProcessor); }
public CommandProcessorMissingOutMapperTests() { _myRequest.RequestValue = "Hello World"; var messageMapperRegistry = new MessageMapperRegistry(new SimpleMessageMapperFactory((type) => { if (type == typeof(MyResponseMessageMapper)) { return(new MyResponseMessageMapper()); } throw new ConfigurationException($"No mapper found for {type.Name}"); })); messageMapperRegistry.Register <MyResponse, MyResponseMessageMapper>(); var subscriberRegistry = new SubscriberRegistry(); subscriberRegistry.Register <MyResponse, MyResponseHandler>(); var handlerFactory = new TestHandlerFactory <MyResponse, MyResponseHandler>(() => new MyResponseHandler()); var retryPolicy = Policy .Handle <Exception>() .Retry(); var circuitBreakerPolicy = Policy .Handle <Exception>() .CircuitBreaker(1, TimeSpan.FromMilliseconds(1)); _commandProcessor = new CommandProcessor( subscriberRegistry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry { { CommandProcessor.RETRYPOLICY, retryPolicy }, { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy } }, messageMapperRegistry, (IAmAMessageProducer) new FakeMessageProducer(), responseChannelFactory: new InMemoryChannelFactory()); PipelineBuilder <MyResponse> .ClearPipelineCache(); }
public CommandProcessorSendWithMultipleMatchesAsyncTests() { var registry = new SubscriberRegistry(); registry.RegisterAsync <MyCommand, MyCommandHandlerAsync>(); registry.RegisterAsync <MyCommand, MyImplicitHandlerAsync>(); var container = new ServiceCollection(); container.AddTransient <MyCommandHandlerAsync>(); container.AddTransient <MyImplicitHandlerAsync>(); container.AddTransient <MyLoggingHandlerAsync <MyCommand> >(); container.AddSingleton(_receivedMessages); var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); _commandProcessor = new CommandProcessor(registry, (IAmAHandlerFactoryAsync)handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry()); PipelineBuilder <MyCommand> .ClearPipelineCache(); }
public FeatureSwitchByConfigMissingConfigStrategySilentOffTests() { _registry = new SubscriberRegistry(); _registry.Register <MyCommand, MyFeatureSwitchedConfigHandler>(); var container = new ServiceCollection(); container.AddSingleton <MyFeatureSwitchedConfigHandler>(); container.AddTransient <FeatureSwitchHandler <MyCommand> >(); container.AddSingleton <IBrighterOptions>(new BrighterOptions() { HandlerLifetime = ServiceLifetime.Transient }); _provider = container.BuildServiceProvider(); _handlerFactory = new ServiceProviderHandlerFactory(_provider); _featureSwitchRegistry = new FakeConfigRegistry(); }
public void Setup() { var logger = new Mock <ILog>().Object; var registry = new SubscriberRegistry(); registry.Register <TestCommand, TestPreAndPostDecoratedHandler>(); var container = new TinyIoCContainer(); var handlerFactory = new TinyIoCHandlerFactory(container); container.Register <IHandleRequests <TestCommand>, TestPreAndPostDecoratedHandler>(); container.Register <IHandleRequests <TestCommand>, TestValidationHandler <TestCommand> >(); container.Register <IHandleRequests <TestCommand>, TestLoggingHandler <TestCommand> >(); container.Register(logger); commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry(), logger); commandProcessor.Send(testCommand); }
public void Setup() { var logger = new Mock <ILog>().Object; var registry = new SubscriberRegistry(); registry.Register <TestCommand, TestImplicitHandler>(); var container = new TinyIoCContainer(); var handlerFactory = new TinyIoCHandlerFactory(container); container.Register <IHandleRequests <TestCommand>, TestImplicitHandler>(); container.Register <IHandleRequests <TestCommand>, TestLoggingHandler <TestCommand> >(); container.Register(logger); pipelineBuilder = new PipelineBuilder <TestCommand>(registry, handlerFactory, logger); pipeline = pipelineBuilder.Build(new RequestContext()).First(); }
public void Setup() { var logger = new Mock <ILog>().Object; var registry = new SubscriberRegistry(); registry.Register <TestCommand, TestFailingDivideByZeroHandler>(); var container = new TinyIoCContainer(); var handlerFactory = new TinyIoCHandlerFactory(container); container.Register <IHandleRequests <TestCommand>, TestFailingDivideByZeroHandler>().AsSingleton(); container.Register <IHandleRequests <TestCommand>, ExceptionPolicyHandler <TestCommand> >().AsSingleton(); container.Register(logger); var policyRegistry = new PolicyRegistry(); var policy = Policy .Handle <DivideByZeroException>() .WaitAndRetry(new[] { 100.Milliseconds(), 200.Milliseconds(), 300.Milliseconds() }, (exception, timeSpan) => { retryCount++; }); policyRegistry.Add("TestDivideByZeroPolicy", policy); TestFailingDivideByZeroHandler.ReceivedCommand = false; commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), policyRegistry, logger); try { commandProcessor.Send(testCommand); } catch (DivideByZeroException) { } }
public ContextBagVisibilityTests() { var registry = new SubscriberRegistry(); registry.Register <MyCommand, MyContextAwareCommandHandler>(); var handlerFactory = new TestHandlerFactory <MyCommand, MyContextAwareCommandHandler>(() => new MyContextAwareCommandHandler()); _request_context = new RequestContext(); _myCommand = new MyCommand(); MyContextAwareCommandHandler.TestString = null; var requestContextFactory = A.Fake <IAmARequestContextFactory>(); A.CallTo(() => requestContextFactory.Create()).Returns(_request_context); _commandProcessor = new CommandProcessor(registry, handlerFactory, requestContextFactory, new PolicyRegistry()); _request_context.Bag["TestString"] = I_AM_A_TEST_OF_THE_CONTEXT_BAG; }
protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); var logger = LogProvider.GetLogger(this.GetType().Namespace); container.Register(logger); var subscriberRegistry = new SubscriberRegistry(); subscriberRegistry.Register <AddTaskCommand, AddTaskCommandHandler>(); subscriberRegistry.Register <CompleteTaskCommand, CompleteTaskCommandHandler>(); container.Register <IHandleRequests <AddTaskCommand>, AddTaskCommandHandler>().AsMultiInstance(); container.Register <IHandleRequests <CompleteTaskCommand>, CompleteTaskCommandHandler>().AsMultiInstance(); var handlerFactory = new TinyIoCHandlerFactory(container); 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 sqlMessageStore = new MsSqlMessageStore(new MsSqlMessageStoreConfiguration("Data Source=|DataDirectory|Tasks.sdf;Persist Security Info=False;", "messages", MsSqlMessageStoreConfiguration.DatabaseType.SqlCe), logger); var gateway = new AzureServiceBusMessageProducer(logger); container.Register <IAmAMessageMapper <TaskReminderCommand>, TaskReminderCommandMessageMapper>().AsMultiInstance(); var messageMapperFactory = new TinyIoCMessageMapperFactory(container); var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory); messageMapperRegistry.Add(typeof(TaskReminderCommand), typeof(TaskReminderCommandMessageMapper)); messageMapperRegistry.Add(typeof(TaskCompletedEvent), typeof(TaskCompletedEventMapper)); var commandProcessor = CommandProcessorBuilder .With() .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory)) .Policies(policyRegistry) .TaskQueues(new MessagingConfiguration(sqlMessageStore, gateway, messageMapperRegistry)) .RequestContextFactory(new InMemoryRequestContextFactory()) .Build(); container.Register <IAmACommandProcessor>(commandProcessor); }
private static async Task MainAsync() { var registry = new SubscriberRegistry(); registry.RegisterAsync<GreetingCommand, GreetingCommandRequestHandlerAsync>(); var builder = CommandProcessorBuilder.With() .Handlers(new HandlerConfiguration(registry, new SimpleHandlerFactoryAsync())) .DefaultPolicy() .NoTaskQueues() .RequestContextFactory(new InMemoryRequestContextFactory()); var commandProcessor = builder.Build(); // To allow the command handler(s) to release the thread // while doing potentially long running operations, // await the async (but inline) handling of the command await commandProcessor.SendAsync(new GreetingCommand("Ian")); Console.ReadLine(); }
private static void Main(string[] args) { var logger = LogProvider.For<Program>(); var dbPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase.Substring(8)), "App_Data\\CommandStore.sdf"); var connectionString = "DataSource=\"" + dbPath + "\""; var configuration = new MsSqlCommandStoreConfiguration(connectionString, "Commands", MsSqlCommandStoreConfiguration.DatabaseType.SqlCe); var commandStore = new MsSqlCommandStore(configuration, logger); var registry = new SubscriberRegistry(); registry.Register<GreetingCommand, GreetingCommandHandler>(); var tinyIoCContainer = new TinyIoCContainer(); tinyIoCContainer.Register<IHandleRequests<GreetingCommand>, GreetingCommandHandler>(); tinyIoCContainer.Register<IAmACommandStore>(commandStore); tinyIoCContainer.Register<ILog>(logger); var builder = CommandProcessorBuilder.With() .Handlers(new HandlerConfiguration( subscriberRegistry: registry, handlerFactory: new TinyIocHandlerFactory(tinyIoCContainer) )) .DefaultPolicy() .Logger(logger) .NoTaskQueues() .RequestContextFactory(new InMemoryRequestContextFactory()); var commandProcessor = builder.Build(); var greetingCommand = new GreetingCommand("Ian"); commandProcessor.Send(greetingCommand); var retrievedCommand = commandStore.Get<GreetingCommand>(greetingCommand.Id); var commandAsJson = JsonConvert.SerializeObject(retrievedCommand); Console.WriteLine(string.Format("Command retrieved from store: {0}", commandAsJson)); Console.ReadLine(); }
private static void Main(string[] args) { var registry = new SubscriberRegistry(); registry.Register<GreetingCommand, GreetingCommandHandler>(); var builder = CommandProcessorBuilder.With() .Handlers(new HandlerConfiguration( subscriberRegistry: registry, handlerFactory: new SimpleHandlerFactory() )) .DefaultPolicy() .NoTaskQueues() .RequestContextFactory(new InMemoryRequestContextFactory()); var commandProcessor = builder.Build(); commandProcessor.Send(new GreetingCommand("Ian")); Console.ReadLine(); }
private static void Main() { var container = new TinyIoCContainer(); var asyncHandlerFactory = new TinyIocHandlerFactory(container); var registry = new SubscriberRegistry(); registry.RegisterAsync<GreetingEvent, WantToBeGreeted>(); registry.RegisterAsync<GreetingEvent, WantToBeGreetedToo>(); var builder = CommandProcessorBuilder.With() .Handlers(new HandlerConfiguration(registry, asyncHandlerFactory)) .DefaultPolicy() .NoTaskQueues() .RequestContextFactory(new InMemoryRequestContextFactory()); var commandProcessor = builder.Build(); // Use bootstrappers for async/await in Console app MainAsync(commandProcessor).Wait(); Console.ReadLine(); }
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)} }; //create the gateway var rmqMessageConsumerFactory = new RmqMessageConsumerFactory("messages"); var rmqMessageProducerFactory = new RmqMessageProducerFactory("messages"); 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) .ProducerFactory(rmqMessageProducerFactory) .ChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory, rmqMessageProducerFactory)) as ControlBusReceiverBuilder; _controlDispatcher = controlBusBuilder.Build(Environment.MachineName + "." + "ManagementAndMonitoring"); 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("monitoring"))); }
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(); }
public static void Run(UnityContainer container) { container.RegisterType<DomainController>(); container.RegisterType<FeedController>(); container.RegisterType<JoinController>(); container.RegisterType<MessageController>(); container.RegisterType<PipeController>(); container.RegisterType<IAmARepository<Domain>, InMemoryDomainRepository>(new ContainerControlledLifetimeManager()); container.RegisterType<IAmARepository<Feed>, InMemoryFeedRepository>(new ContainerControlledLifetimeManager()); container.RegisterType<IAmARepository<Pipe>, InMemoryPipeRepository>(new ContainerControlledLifetimeManager()); container.RegisterType<IAmARepository<Join>, InMemoryJoinRepository>(new ContainerControlledLifetimeManager()); container.RegisterType<IAmACredentialStore, CredentialStore>(new ContainerControlledLifetimeManager()); container.RegisterInstance(typeof(ILog), LogProvider.For<RestMSService>(), new ContainerControlledLifetimeManager()); container.RegisterType<AddFeedCommandHandler>(); container.RegisterType<AddFeedToDomainCommandHandler>(); container.RegisterType<AddJoinCommandHandler>(); container.RegisterType<AddJoinToFeedCommandHandler>(); container.RegisterType<AddJoinToPipeCommandHandler>(); container.RegisterType<AddMessageToFeedCommandHandler>(); container.RegisterType<AddPipeCommandHandler>(); container.RegisterType<AddPipeToDomainCommandHandler>(); container.RegisterType<DeleteFeedCommandHandler>(); container.RegisterType<DeleteMessageCommandHandler>(); container.RegisterType<DeletePipeCommandHandler>(); container.RegisterType<RemoveFeedFromDomainCommandHandler>(); container.RegisterType<CacheCleaningHandler>(); var handlerFactory = new UnityHandlerFactory(container); var subscriberRegistry = new SubscriberRegistry { {typeof(AddFeedCommand), typeof(AddFeedCommandHandler)}, {typeof(AddFeedToDomainCommand), typeof(AddFeedToDomainCommandHandler)}, {typeof(AddJoinCommand), typeof(AddJoinCommandHandler)}, {typeof(AddJoinToFeedCommand), typeof(AddJoinToFeedCommandHandler)}, {typeof(AddJoinToPipeCommand), typeof(AddJoinToPipeCommandHandler)}, {typeof(AddMessageToFeedCommand), typeof(AddMessageToFeedCommandHandler)}, {typeof(AddPipeCommand), typeof(AddPipeCommandHandler)}, {typeof(AddPipeToDomainCommand), typeof(AddPipeToDomainCommandHandler)}, {typeof(DeleteFeedCommand), typeof(DeleteFeedCommandHandler)}, {typeof(DeleteMessageCommand), typeof(DeleteMessageCommandHandler)}, {typeof(DeletePipeCommand), typeof(DeletePipeCommandHandler)}, {typeof(RemoveFeedFromDomainCommand), typeof(RemoveFeedFromDomainCommandHandler)}, {typeof(InvalidateCacheCommand), typeof(CacheCleaningHandler)} }; //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(container.Resolve<ILog>()) .NoTaskQueues() .RequestContextFactory(new InMemoryRequestContextFactory()) .Build(); container.RegisterInstance(typeof(IAmACommandProcessor), commandProcessor); }
/// <summary> /// Builds this instance. /// </summary> /// <param name="hostName">Name of the host.</param> /// <returns>Dispatcher.</returns> 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, IsDurable = true, DataType = typeof(ConfigurationCommand).FullName, RoutingKey = hostName + "." + CONFIGURATION, }; connections.Add(configurationElement); var heartbeatElement = new ConnectionElement { ChannelName = HEARTBEAT, ConnectionName = HEARTBEAT, IsDurable = false, DataType = typeof(HeartBeatCommand).FullName, RoutingKey = hostName + "." + HEARTBEAT, }; connections.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>(); var messageMapperRegistry = new MessageMapperRegistry(new ControlBusMessageMapperFactory()); messageMapperRegistry.Register<ConfigurationCommand, ConfigurationCommandMessageMapper>(); var commandProcessor = CommandProcessorBuilder.With() .Handlers(new HandlerConfiguration(subscriberRegistry, new ControlBusHandlerFactory(_dispatcher, _logger))) .Policies(policyRegistry) .NoTaskQueues() .RequestContextFactory(new InMemoryRequestContextFactory()) .Build(); return DispatchBuilder .With() .CommandProcessor(commandProcessor) .MessageMappers(messageMapperRegistry) .ChannelFactory(_channelFactory) .ConnectionsFromElements(connections) .Build(); }
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 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 ); // 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); var dispatcher = builder.Build(); dispatcher.Receive(); Console.WriteLine("Press Enter to stop ..."); Console.ReadLine(); dispatcher.End().Wait(); }
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(); }
private PipelineContinuation InitializeContainer(ICommunicationContext arg) { var container = new TinyIoCContainer(); container.Register<IHandleRequests<AddTaskCommand>, AddTaskCommandHandler>().AsMultiInstance(); container.Register<ITaskListRetriever, TaskListRetriever>().AsMultiInstance(); container.Register<ITasksDAO, TasksDAO>().AsMultiInstance(); var logger = LogManager.GetLogger("TaskList"); container.Register<ILog, ILog>(logger); container.Register<IAmARequestContextFactory, InMemoryRequestContextFactory>().AsMultiInstance(); container.Register<IAmAMessageStore<Message>, RavenMessageStore>().AsSingleton(); container.Register<IAmAMessagingGateway, RMQMessagingGateway>().AsSingleton(); var handlerFactory = new TinyIocHandlerFactory(container); var messageMapperFactory = new TinyIoCMessageMapperFactory(container); var subscriberRegistry = new SubscriberRegistry(); subscriberRegistry.Register<AddTaskCommand, AddTaskCommandHandler>(); //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); //create the gateway var gateway = new RMQMessagingGateway(logger); var commandProcessor = CommandProcessorBuilder.With() .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory)) .Policies(policyRegistry) .Logger(logger) .TaskQueues(new MessagingConfiguration( messageStore: new RavenMessageStore(new EmbeddableDocumentStore(), logger), messagingGateway: gateway, messageMapperRegistry: messageMapperRegistry )) .RequestContextFactory(new InMemoryRequestContextFactory()) .Build(); resolver.AddDependencyInstance<IAmACommandProcessor>(commandProcessor, DependencyLifetime.Singleton); resolver.AddDependency<ITaskRetriever, TaskRetriever>(DependencyLifetime.Singleton); resolver.AddDependency<ITaskListRetriever, TaskListRetriever>(DependencyLifetime.Singleton); return PipelineContinuation.Continue; }
public TaskMailerService() { log4net.Config.XmlConfigurator.Configure(); var logger = LogProvider.For<TaskMailerService>(); var container = new TinyIoCContainer(); container.Register<IAmAMessageMapper<TaskReminderCommand>, TaskReminderCommandMessageMapper>(); container.Register<MailTaskReminderHandler, MailTaskReminderHandler>(); 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, 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 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); var rmqMessageProducerFactory = new RmqMessageProducerFactory(logger); _dispatcher = DispatchBuilder.With() .Logger(logger) .CommandProcessor(commandProcessor) .MessageMappers(messageMapperRegistry) .ChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory, rmqMessageProducerFactory)) .ConnectionsFromConfiguration() .Build(); }
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) .ChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory, rmqMessageProducerFactory)) .Connections(connections); _dispatcher = builder.Build(); var controlBusBuilder = ControlBusReceiverBuilder .With() .Dispatcher(_dispatcher) .ProducerFactory(rmqMessageProducerFactory) .ChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory, rmqMessageProducerFactory)) 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))); }
public IServiceProvider ConfigureServices(IServiceCollection services) { // Add framework serviceProvider. services.AddMvc(); services.AddSingleton<ITaskListRetriever, TaskListRetriever>(); services.AddSingleton<ITaskRetriever, TaskRetriever>(); services.AddSingleton<ITasksDAO, TasksDAO>(); //create handler var subscriberRegistry = new SubscriberRegistry(); services.AddTransient<IHandleRequests<AddTaskCommand>, AddTaskCommandHandler>(); subscriberRegistry.Register<AddTaskCommand, AddTaskCommandHandler>(); //complete handler services.AddTransient<IHandleRequests<CompleteTaskCommand>, CompleteTaskCommandHandler>(); subscriberRegistry.Register<CompleteTaskCommand, CompleteTaskCommandHandler>(); //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 services.AddTransient<IAmAMessageMapper<TaskReminderCommand>, TaskReminderCommandMessageMapper>(); var messagingGatewayConfiguration = RmqGatewayBuilder.With.Uri(new Uri(Configuration["RabbitMQ:Uri"])).Exchange(Configuration["RabbitMQ:Exchange"]).DefaultQueues(); var gateway = new RmqMessageProducer(messagingGatewayConfiguration); IAmAMessageStore<Message> sqlMessageStore = new SqliteMessageStore(new SqliteMessageStoreConfiguration("Data Source = tasks.db", "MessageStores")); var container = new Container(); container.Configure(config => { var servicesMessageMapperFactory = new ServicesMessageMapperFactory(container); var messageMapperRegistry = new MessageMapperRegistry(servicesMessageMapperFactory) { {typeof(TaskReminderCommand), typeof(TaskReminderCommandMessageMapper)}, {typeof(TaskAddedEvent), typeof(TaskAddedEventMapper)}, {typeof(TaskEditedEvent), typeof(TaskEditedEventMapper)}, {typeof(TaskCompletedEvent), typeof(TaskCompletedEventMapper)}, {typeof(TaskReminderSentEvent), typeof(TaskReminderSentEventMapper)} }; var servicesHandlerFactory = new ServicesHandlerFactory(container); var commandProcessor = CommandProcessorBuilder.With() .Handlers(new HandlerConfiguration(subscriberRegistry, servicesHandlerFactory)) .Policies(policyRegistry) .TaskQueues(new MessagingConfiguration(sqlMessageStore, gateway, messageMapperRegistry)) .RequestContextFactory(new InMemoryRequestContextFactory()) .Build(); config.For<IAmACommandProcessor>().Singleton().Use(() => commandProcessor); }); container.Populate(services); return container.GetInstance<IServiceProvider>(); }
public DocumentService() { log4net.Config.XmlConfigurator.Configure(); var container = new TinyIoCContainer(); var handlerFactory = new TinyIocHandlerFactory(container); var messageMapperFactory = new TinyIoCMessageMapperFactory(container); container.Register<IHandleRequests<DocumentCreatedEvent>, DocumentCreatedEventHandler>(); container.Register<IHandleRequests<DocumentUpdatedEvent>, DocumentUpdatedEventHandler>(); container.Register<IHandleRequests<FolderCreatedEvent>, FolderCreatedEventHandler>(); var subscriberRegistry = new SubscriberRegistry(); subscriberRegistry.Register<DocumentCreatedEvent, DocumentCreatedEventHandler>(); subscriberRegistry.Register<DocumentUpdatedEvent, DocumentUpdatedEventHandler>(); subscriberRegistry.Register<FolderCreatedEvent, FolderCreatedEventHandler>(); //create policies var retryPolicy = Policy .Handle<Exception>() .WaitAndRetry(new[] { TimeSpan.FromMilliseconds(5000), TimeSpan.FromMilliseconds(10000), TimeSpan.FromMilliseconds(10000) }); 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(FolderCreatedEvent), typeof(FolderCreatedEventMessageMapper)}, {typeof(DocumentCreatedEvent), typeof(DocumentCreatedEventMessageMapper)}, {typeof(DocumentUpdatedEvent), typeof(DocumentUpdatedEventMessageMapper)} }; var awsCredentials = new StoredProfileAWSCredentials(); var sqsMessageConsumerFactory = new SqsMessageConsumerFactory(awsCredentials ); var sqsMessageProducerFactory = new SqsMessageProducerFactory(awsCredentials ); var connections = new List<paramore.brighter.serviceactivator.Connection> { new paramore.brighter.serviceactivator.Connection( new ConnectionName("paramore.example.documentsandfolders.documentcreatedevent"), new InputChannelFactory(sqsMessageConsumerFactory, sqsMessageProducerFactory), typeof(DocumentCreatedEvent), new ChannelName("https://sqs.eu-west-1.amazonaws.com/027649620536/DocumentCreatedEvent"), "DocumentCreatedEvent", timeoutInMilliseconds: 5000, noOfPerformers: 10), new paramore.brighter.serviceactivator.Connection( new ConnectionName("paramore.example.documentsandfolders.documentupdatedevent"), new InputChannelFactory(sqsMessageConsumerFactory, sqsMessageProducerFactory), typeof(DocumentUpdatedEvent), new ChannelName("https://sqs.eu-west-1.amazonaws.com/027649620536/DocumentUpdatedEvent"), "DocumentUpdatedEvent", timeoutInMilliseconds: 5000, noOfPerformers: 10), new paramore.brighter.serviceactivator.Connection( new ConnectionName("paramore.example.documentsandfolders.foldercreateddevent"), new InputChannelFactory(sqsMessageConsumerFactory, sqsMessageProducerFactory), typeof(FolderCreatedEvent), new ChannelName("https://sqs.eu-west-1.amazonaws.com/027649620536/FolderCreatedEvent"), "FolderCreatedEvent", timeoutInMilliseconds: 5000, noOfPerformers: 10) }; var builder = DispatchBuilder .With() .CommandProcessor(CommandProcessorBuilder.With() .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory)) .Policies(policyRegistry) .NoTaskQueues() .RequestContextFactory(new InMemoryRequestContextFactory()) .Build() ) .MessageMappers(messageMapperRegistry) .ChannelFactory(new InputChannelFactory(sqsMessageConsumerFactory, sqsMessageProducerFactory)) .Connections(connections); _dispatcher = builder.Build(); }
public static void Main() { Log.Logger = new LoggerConfiguration() .WriteTo.Console() .CreateLogger(); 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 = RmqGatewayBuilder.With .Uri(new Uri("amqp://*****:*****@localhost:5672/%2f")) .Exchange("paramore.brighter.exchange") .DefaultQueues(); var rmqMessageProducerFactory = new RmqMessageProducerFactory(rmqGatewayMessages); var inputChannelFactory = new InputChannelFactory(new RmqMessageConsumerFactory(rmqGatewayMessages), rmqMessageProducerFactory); var builder = DispatchBuilder .With() .CommandProcessor(CommandProcessorBuilder.With() .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory)) .Policies(policyRegistry) .NoTaskQueues() .RequestContextFactory(new InMemoryRequestContextFactory()) .Build() ) .MessageMappers(messageMapperRegistry) .ChannelFactory(inputChannelFactory) .Connections(new[] { ConnectionBuilder.With .Name("paramore.example.greeting") .ChannelFactory(inputChannelFactory) .Type(typeof(GreetingCommand)) .ChannelName("greeting.event") .RoutingKey("greeting.event") .Timeout(200) .Build() }); _dispatcher = builder.Build(); var controlBusBuilder = ControlBusReceiverBuilder .With() .Dispatcher(_dispatcher) .ProducerFactory(rmqMessageProducerFactory) .ChannelFactory(inputChannelFactory) as ControlBusReceiverBuilder; var 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(RmqGatewayBuilder.With .Uri(new Uri("amqp://*****:*****@localhost:5672/%2f")) .Exchange("paramore.brighter.exchange") .DefaultQueues()))); controlDispatcher.Receive(); _dispatcher.Receive(); Console.WriteLine("Press Enter to stop ..."); Console.ReadLine(); controlDispatcher.End(); //Don't wait on the control bus, we are stopping so we don't want any more control messages, just terminate _dispatcher.End().Wait(); }
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>(); var handlerFactory = new TinyIocHandlerFactory(container); var subscriberRegistry = new SubscriberRegistry(); //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 = //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(), logger), messagingGateway: gateway, messageMapperRegistry: null )) .RequestContextFactory(new InMemoryRequestContextFactory()) .Build() ) .WithMessageMappers(null) .WithChannelFactory(new RMQInputChannelfactory(gateway)) .ConnectionsFromConfiguration(); dispatcher = builder.Build(); }