Exemplo n.º 1
0
        public MessagingModule()
        {
            Get["/send"] = parameters =>
            {
                return(View["SendMessage.sshtml"]);
            };

            Get["/send/command/{messagetype}"] = parameters =>
            {
                //code to send the message on Mass Transit
                var queueName = "rabbitmq://localhost/commandqueue";
                var bus       = ServiceBusFactory.New(configurator =>
                {
                    configurator.UseRabbitMq();
                    configurator.ReceiveFrom(queueName);
                });

                bus.Publish(new MakeAnElection
                {
                    AdministratorCode = "admcode",
                    CompanyCode       = "cocode",
                    ParticipantId     = "empnum",
                    ElectionAmount    = 1200,
                    ElectionReason    = "reason",
                });

                return(View["SendMessage.sshtml"]);
            };
        }
        public void Endpoint_receive_should_select_encrypted_serializer_based_on_content_type()
        {
            var          serializer  = new PreSharedKeyEncryptedMessageSerializer(_key, new TSerializer());
            var          pingMessage = new PingMessage(Guid.NewGuid());
            const string self        = "loopback://127.0.0.1/self";

            using (var bus = ServiceBusFactory.New(sbc =>
            {
                sbc.ReceiveFrom(self);
                // Ensure outbound message are serialized and encrypted
                sbc.SetDefaultSerializer(serializer);
                sbc.Subscribe(s => s.Handler <PingMessage>((context, message) => context.Respond(new PongMessage(message.CorrelationId))));
            }))
            {
                var selfEndpoint = bus.GetEndpoint(new Uri(self));
                selfEndpoint.ShouldNotBeNull();

                try
                {
                    selfEndpoint.SendRequest(pingMessage, bus, x =>
                    {
                        x.SetTimeout(TimeSpan.FromSeconds(5));
                        x.Handle <PongMessage>(pongMsg => pongMsg.CorrelationId.ShouldEqual(pingMessage.CorrelationId));
                    });
                }
                catch (Exception e)
                {
                    Assert.Fail(e.ToString());
                }
            }
        }
Exemplo n.º 3
0
        public void Setup()
        {
            if (_endpointFactoryConfigurator != null)
            {
                ConfigurationResult result = ConfigurationResultImpl.CompileResults(_endpointFactoryConfigurator.Validate());

                try
                {
                    EndpointFactory = _endpointFactoryConfigurator.CreateEndpointFactory();
                    _endpointCache  = new EndpointCache(EndpointFactory);
                    EndpointCache   = new EndpointCacheProxy(_endpointCache);
                }
                catch (Exception ex)
                {
                    throw new ConfigurationException(result, "An exception was thrown during endpoint cache creation", ex);
                }
            }

            ServiceBusFactory.ConfigureDefaultSettings(x =>
            {
                x.SetEndpointCache(EndpointCache);
                x.SetConcurrentConsumerLimit(4);
                x.SetReceiveTimeout(TimeSpan.FromMilliseconds(50));
                x.EnableAutoStart();
                x.DisablePerformanceCounters();
            });

            EstablishContext();
        }
Exemplo n.º 4
0
        public override void Load()
        {
            Bind <ISagaRepository <OrderSaga> >()
            .To <InMemorySagaRepository <OrderSaga> >()
            .InSingletonScope();

            Bind <OrderService>()
            .To <OrderService>()
            .InSingletonScope();

            Bind <IServiceBus>().ToMethod(context =>
            {
                return(ServiceBusFactory.New(sbc =>
                {
                    sbc.UseMsmq();
                    sbc.UseMulticastSubscriptionClient();
                    sbc.ReceiveFrom("msmq://localhost/starbucks_cashier");
                    sbc.SetConcurrentConsumerLimit(1);                                                                   //a cashier cannot multi-task

                    sbc.UseControlBus();
                    sbc.EnableRemoteIntrospection();
                }));
            })
            .InSingletonScope();
        }
Exemplo n.º 5
0
        public void Setup_quartz_service()
        {
            ISchedulerFactory schedulerFactory = new StdSchedulerFactory();

            _scheduler = schedulerFactory.GetScheduler();

            _receivedA = new ManualResetEvent(false);

            _bus = ServiceBusFactory.New(x =>
            {
                x.ReceiveFrom("loopback://localhost/quartz");
                x.UseJsonSerializer();

                x.Subscribe(s =>
                {
                    s.Handler <A>((msg, context) =>
                    {
                        _received = msg;
                        _receivedA.Set();
                    });
                    s.Consumer(() => new ScheduleMessageConsumer(_scheduler));
                });
            });

            _scheduler.JobFactory = new MassTransitJobFactory(_bus);
            _scheduler.Start();
        }
Exemplo n.º 6
0
        public Form1()
        {
            //deviceService = new NetworkDeviceService();

            InitializeComponent();

            serviceBus = ServiceBusFactory.New(cfg =>
            {
                cfg.ReceiveFrom("rabbitmq://localhost/cqrs-poc");
                cfg.UseRabbitMq(cf =>
                {
                    cf.ConfigureHost(new Uri("rabbitmq://localhost/cqrs-poc"), hc =>
                    {
                        hc.SetUsername("petcar");
                        hc.SetPassword("?!Krone2009");
                    });
                });
            });

            commandPublisher = new CommandPublisher(serviceBus);
            service          = new NetworkDeviceService(commandPublisher);
            ndvb             = new NetworkDeviceViewBuilder();

            serviceBus.SubscribeHandler <HandlerNotification>(service.Handle);

            //service.ServiceResultRecieved += (sender, result) =>
            //{
            //    var a = result;
            //};

            service.ServiceResultRecieved += service_ServiceResultRecieved;

            GetDevices();
        }
Exemplo n.º 7
0
        public void Setup_quartz_service()
        {
            ISchedulerFactory schedulerFactory = new StdSchedulerFactory();

            _scheduler = schedulerFactory.GetScheduler();

            _receivedA  = new ManualResetEvent(false);
            _receivedIA = new ManualResetEvent(false);

            _bus = ServiceBusFactory.New(x =>
            {
                x.ReceiveFrom("loopback://localhost/quartz");
                x.UseXmlSerializer();
                x.SetConcurrentConsumerLimit(1);

                x.Subscribe(s =>
                {
                    s.Handler <A>(msg => _receivedA.Set());
                    s.Handler <IA>(msg => _receivedIA.Set());
                    s.Consumer(() => new ScheduleMessageConsumer(_scheduler));
                    s.Consumer(() => new CancelScheduledMessageConsumer(_scheduler));
                });
            });

            _scheduler.JobFactory = new MassTransitJobFactory(_bus);
            _scheduler.Start();
        }
Exemplo n.º 8
0
        static void Main()
        {
            Log4NetLogger.Use("customer.log4net.xml");

            //IContainer c = BootstrapContainer();

            var container = new UnityContainer();

            // register types directly
            container.RegisterType <OrderDrinkForm>(new ContainerControlledLifetimeManager());
            container.RegisterType(typeof(ISagaRepository <>), typeof(InMemorySagaRepository <>), new ContainerControlledLifetimeManager());

            // Register the ServiceBus.
            container.RegisterInstance <IServiceBus>(ServiceBusFactory.New(sbc =>
            {
                // Configure exchanges.
                sbc.ReceiveFrom("msmq://localhost/starbucks_customer");
                sbc.UseMsmq();
                sbc.UseMulticastSubscriptionClient();
                sbc.UseControlBus();

                sbc.Subscribe(subs => { subs.LoadFrom(container); });
            }));

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new OrderDrinkForm(container.Resolve <IServiceBus>()));
            //Application.Run(new OrderDrinkForm(container.GetInstance<IServiceBus>()));
        }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            IServiceBus bus = ServiceBusFactory.New(cfg =>
            {
                cfg.DisablePerformanceCounters();
                cfg.ReceiveFrom("rabbitmq://localhost/qqqq-app");
                cfg.UseRabbitMq(cf =>
                {
                    cf.ConfigureHost(new Uri("rabbitmq://localhost/qqqq-app"), hc =>
                    {
                        hc.SetUsername("petcar");
                        hc.SetPassword("?!Krone2009");
                    });
                });
            });

            EventPublisher publisher = new EventPublisher(bus);

            TheCommandHandler handler = new TheCommandHandler(publisher);

            bus.SubscribeHandler <AddItemCommand>(handler.Handle);
            bus.SubscribeHandler <UpdateItemCommand>(handler.Handle);
            bus.SubscribeHandler <DeleteItemCommand>(handler.Handle);

            Console.ReadKey();
        }
Exemplo n.º 10
0
        public void StartConsumer()
        {
            if (_consumerbusBuses != null)
            {
                return;
            }

            lock (lockObject)
            {
                if (_consumerbusBuses != null)
                {
                    return;
                }

                _consumerbusBuses = new List <IServiceBus>();

                var messageTextBus = ServiceBusFactory.New(x =>
                {
                    x.UseRabbitMq();
                    x.ReceiveFrom("rabbitmq://localhost/poc_message_messageText_queue");
                });

                messageTextBus.SubscribeConsumer <MessageTextProcessor>();
                _consumerbusBuses.Add(messageTextBus);

                var timeToProcessBus = ServiceBusFactory.New(x =>
                {
                    x.UseRabbitMq();
                    x.ReceiveFrom("rabbitmq://localhost/poc_message_timeToProcess_queue");
                });
                timeToProcessBus.SubscribeConsumer <TimeToProcessConsumer>();
                _consumerbusBuses.Add(timeToProcessBus);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// 需要消费Event
        /// </summary>
        /// <param name="host">服务器ip</param>
        /// <param name="queue">Queue名称</param>
        /// <param name="concurrentConsumers">消费者数量</param>
        /// <param name="configurator">消费者的配置对象</param>
        public void SubscribeAt(string host, string queue, int concurrentConsumers, IConsumeConfigurator configurator)
        {
            var endpoint       = string.Format("rabbitmq://{0}/{1}", host, queue);
            var rabbitEndpoint = new[] { host };
            var consumers      = GetQueueConsumers(queue);
            var bus            = ServiceBusFactory.New(sbc =>
            {
                sbc.ReceiveFrom(endpoint);

                sbc.UseRabbitMq(
                    x =>
                {
                    x.UseRoundRobinConnectionPolicy(rabbitEndpoint);
                    x.PersistMessages(true);
                }
                    );

                sbc.SetConcurrentConsumerLimit(concurrentConsumers);
                sbc.Subscribe(x => configurator.Configure(x, consumers));
            });

            //var publisher = new EventPublisher(bus);
            //_reg.Inject<IEventPublisher>(publisher);

            // 记录消费者服务总线对象
            var consumerBus = new EventConsumerBus(bus);

            _reg.Inject <IEventConsumerBus>(consumerBus);
        }
Exemplo n.º 12
0
        public void Execute(IContainer container)
        {
            log4net.Config.XmlConfigurator.Configure();

            container.Configure(x =>
            {
                x.Scan(scanner =>
                {
                    scanner.AssembliesFromApplicationBaseDirectory(assembly => assembly.GetName().Name.StartsWith("Example"));
                    scanner.AddAllTypesOf(typeof(IStartup));
                    scanner.AddAllTypesOf(typeof(IConsumer));
                    scanner.SingleImplementationsOfInterface();
                    scanner.WithDefaultConventions();
                });
                x.For <ILog>().Use(LogManager.GetLogger(typeof(StartupTask)));
            });

            foreach (var task in container.GetAllInstances <IStartup>())
            {
                task.Execute(container);
            }

            // must be done out of the normal configuration due to the dependence on the
            // scan for consumers having been completed.
            container.Inject(typeof(IServiceBus),
                             ServiceBusFactory.New(sbc =>
            {
                sbc.UseRabbitMq();
                sbc.UseControlBus();
                sbc.ReceiveFrom(ConfigurationManager.AppSettings["WebDenormalizerMessageQueue"]);
                sbc.Subscribe(subs => subs.LoadFrom(container));
            }));
        }
Exemplo n.º 13
0
        protected override void ConfigureApplicationContainer(ILifetimeScope container)
        {
            base.ConfigureApplicationContainer(container);

            var builder = new ContainerBuilder();

            builder.RegisterType <AppSettings>().As <IAppSettings>().SingleInstance();
            builder.RegisterType <DummyMailChimpWebhooks>().As <IMailChimpWebhooks>().SingleInstance();
            builder.RegisterType <DummyMailgunWebhooks>().As <IMailgunWebhooks>().SingleInstance();
            builder.RegisterType <AzureTableStorageTodoService>().As <ITodoService>().SingleInstance();

            // Consumers and sagas
            builder.RegisterAssemblyTypes(typeof(Bootstrapper).Assembly)
            .Where(t => t.Implements <ISaga>() ||
                   t.Implements <IConsumer>())
            .AsSelf();

            // Saga repositories
            builder.RegisterGeneric(typeof(InMemorySagaRepository <>))
            .As(typeof(ISagaRepository <>))
            .SingleInstance();

            // Service bus
            builder.Register(c => ServiceBusFactory.New(sbc =>
            {
                sbc.ReceiveFrom("loopback://localhost/queue");
                sbc.Subscribe(x => x.LoadFrom(container));
            })).As <IServiceBus>().SingleInstance();

            builder.Update(container.ComponentRegistry);
        }
Exemplo n.º 14
0
        public IServiceBus Start(ITransportConfigurator transportConfigurator)
        {
            OnStarting();

            try
            {
                _log.InfoFormat("{0} Starting Service Bus for Queue: {1}({2})", GetType().GetServiceDescription(), _queueName, _consumerLimit);

                IServiceBus bus = ServiceBusFactory.New(x =>
                {
                    transportConfigurator.Configure(x, _queueName, _consumerLimit);

                    x.Subscribe(s =>
                    {
                        foreach (SubscriptionBusServiceBuilderConfigurator builderConfigurator in _configurators)
                        {
                            s.AddConfigurator(builderConfigurator);
                        }
                    });
                });

                OnStarted(bus);

                _bus = bus;

                return(bus);
            }
            catch (Exception ex)
            {
                OnStartFailed(ex);
                throw;
            }
        }
        public TimeoutServiceRegistry(IContainer container)
        {
            var configuration = container.GetInstance <IConfiguration>();

            For <ISessionFactory>()
            .Singleton()
            .Use(context => CreateSessionFactory());

            For(typeof(ISagaRepository <>))
            .Add(typeof(NHibernateSagaRepository <>));

            For <IServiceBus>()
            .Singleton()
            .Use(context =>
            {
                return(ServiceBusFactory.New(sbc =>
                {
                    sbc.ReceiveFrom(configuration.TimeoutServiceDataUri);
                    sbc.UseControlBus();
                    sbc.UseLog4Net();

                    sbc.UseMsmq(x => x.UseSubscriptionService(configuration.SubscriptionServiceUri));

                    sbc.SetConcurrentConsumerLimit(1);

                    if (configuration.HealthServiceEnabled)
                    {
                        sbc.UseHealthMonitoring(10);
                    }
                }));
            });
        }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            var builder = new ContainerBuilder();

            // register each consumer manually
            builder.RegisterType <PickConsumer>().AsSelf();

            //or use Autofac's scanning capabilities -- SomeClass is any class in the correct assembly
            //builder.RegisterAssemblyTypes(typeof(PickConsumer).Assembly)
            //    .Where(t => t.Implements<IConsumer>())
            //    .AsSelf();

            //now we add the bus
            builder.Register(c => ServiceBusFactory.New(sbc =>
            {
                sbc.UseRabbitMq();
                sbc.ReceiveFrom(BusInitializer.GetUri("PickService"));

                //this will find all of the consumers in the container and
                //register them with the bus.
                sbc.Subscribe(x => x.LoadFrom(c.Resolve <ILifetimeScope>()));
            })).As <IServiceBus>().SingleInstance().AutoActivate();

            builder.Build();

            Console.WriteLine("Waiting..");
            Console.ReadKey();
        }
        public void ActivityTestFixtureFixtureTeardown()
        {
            foreach (ActivityTestContext activityTestContext in ActivityTestContexts.Values)
            {
                activityTestContext.Dispose();
            }

            LocalBus.Dispose();

            if (_cancellationTokenSource != null)
            {
                _cancellationTokenSource.Dispose();
            }
            if (_timer != null)
            {
                _timer.Dispose();
            }

            _endpointCache.Clear();

            if (EndpointCache != null)
            {
                EndpointCache.Dispose();
                EndpointCache = null;
            }

            ServiceBusFactory.ConfigureDefaultSettings(x => { x.SetEndpointCache(null); });
        }
Exemplo n.º 18
0
        public void Should_support_the_username_password_for_a_host()
        {
            var inputAddress = new Uri("rabbitmq://localhost/mt/test_queue");
            var future       = new Future <IConsumeContext <A> >();

            using (IServiceBus bus = ServiceBusFactory.New(c =>
            {
                c.ReceiveFrom(inputAddress);
                c.UseRabbitMq(r =>
                {
                    r.ConfigureHost(inputAddress, h =>
                    {
                        h.SetUsername("testUser");
                        h.SetPassword("test");
                    });
                });

                c.Subscribe(s => s.Handler <A>((context, message) => future.Complete(context)));
            }))
            {
                bus.Publish(new A());

                Assert.IsTrue(future.WaitUntilCompleted(TimeSpan.FromSeconds(8)));
            }

            Assert.AreEqual(inputAddress.ToString(), future.Value.SourceAddress.ToString());
        }
Exemplo n.º 19
0
        private static IContainer BootstrapContainer(TransportSettings transportSettings, string appNameBase)
        {
            ObjectFactory.Initialize(cfg =>
            {
                cfg.AddRegistry <CentralMonRegistry>();

                cfg.For <TransportSettings>().Singleton().Use(transportSettings);

                cfg.For <IServiceBus>().Use(context => ServiceBusFactory.New(sbc =>
                {
                    string rcvQueueUri = transportSettings.GetQueueUri(appNameBase);
                    sbc.ReceiveFrom(rcvQueueUri);

                    transportSettings.ApplyGlobalConfig(sbc);

                    sbc.UseControlBus();

                    sbc.Subscribe(sub =>
                    {
                        sub.LoadFrom(ObjectFactory.Container);
                    });
                }));
            });

            var container = ObjectFactory.Container;

            CentralMonRegistry.Build(container);
            return(container);
        }
        public void an_interface_based_message_is_published()
        {
            _receivedAnyRat = new Future <TMesg>();

            var details = new AccountDetails();

            _publisherBus = ServiceBusFactory.New(sbc =>
            {
                sbc.ReceiveFrom(details.BuildUri("When_publishing_ordinary_interfaces_publisher"));
                sbc.SetPurgeOnStartup(true);
                sbc.UseAzureServiceBus();
                sbc.UseAzureServiceBusRouting();
            });

            _subscriberBus = ServiceBusFactory.New(sbc =>
            {
                sbc.ReceiveFrom(details.BuildUri("When_publishing_ordinary_interfaces_subscriber"));
                sbc.SetPurgeOnStartup(true);
                sbc.Subscribe(s => s.Handler <TMesg>(_receivedAnyRat.Complete).Transient());
                sbc.UseAzureServiceBus();
                sbc.UseAzureServiceBusRouting();
            });

            // wait for the inbound transport to become ready before publishing
            _subscriberBus.Endpoint.InboundTransport.Receive(c1 => c2 => { }, 1.Milliseconds());

            _publisherBus.Publish <TMesg>(new
            {
                SoundsLike = "peep"
            });

            _receivedAnyRat.WaitUntilCompleted(35.Seconds()).ShouldBeTrue();
        }
Exemplo n.º 21
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging(loggingBuilder => loggingBuilder
                                .AddConsole()
                                .SetMinimumLevel(LogLevel.Debug));
            services.AddDbContext<SeasonParticipantsDb>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddMvc(x => x.EnableEndpointRouting = false)
                    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddCors();
            services.AddSwaggerDocument();
            services.Configure<BusSettings>(Configuration.GetSection("ServiceBus"));
           
            services.AddTransient<Func<string, IBusClient>>(serviceProvider => key =>
            {
                switch (key)
                {
                    case "NewClubSeason":
                        return ServiceBusFactory.GetBus(Enum.Parse<BusHost>(Configuration.GetSection("ServiceBus")["ServiceBusHost"]),
                                                                           Configuration.GetSection("ServiceBus")["ServiceBusConnectionString"],
                                                                           Configuration.GetSection("ServiceBus")["NewClubSeasonAssociationTopicName"],
                                                                           Configuration.GetSection("ServiceBus")["NewClubSeasonAssociationSubscriptionName"]);
                    case "NewSeason":
                        return ServiceBusFactory.GetBus(Enum.Parse<BusHost>(Configuration.GetSection("ServiceBus")["ServiceBusHost"]),
                                                                           Configuration.GetSection("ServiceBus")["ServiceBusConnectionString"],
                                                                           Configuration.GetSection("ServiceBus")["NewSeasonTopicName"],
                                                                           Configuration.GetSection("ServiceBus")["NewSeasonSubscriptionName"]);
                    default:
                        throw new InvalidOperationException("Specified bus type does not exist!");
                }
            });

        }
        public void an_interface_based_message_is_published()
        {
            _receivedAnyRat = new Future <CorrelatedSwedishRat>();

            var details = new AccountDetails();

            _publisherBus = ServiceBusFactory.New(sbc =>
            {
                sbc.ReceiveFrom(details.BuildUri("When_publishing_correlated_interface_publisher"));
                sbc.SetPurgeOnStartup(true);
                sbc.UseAzureServiceBus();
                sbc.UseAzureServiceBusRouting();
            });

            _subscriberBus = ServiceBusFactory.New(sbc =>
            {
                sbc.ReceiveFrom(details.BuildUri("When_publishing_correlated_interface_subscriber"));
                sbc.SetPurgeOnStartup(true);
                sbc.Subscribe(s => s.Handler <CorrelatedSwedishRat>(_receivedAnyRat.Complete).Transient());
                sbc.UseAzureServiceBus();
                sbc.UseAzureServiceBusRouting();
            });

            // wait for the inbound transport to become ready before publishing
            _subscriberBus.Endpoint.InboundTransport.Receive(c1 => c2 => { }, 1.Milliseconds());

            correlationId = CombGuid.Generate();
            _publisherBus.Publish <CorrelatedSwedishRat>(new CorrImpl(correlationId, "meek"));

            _receivedAnyRat.WaitUntilCompleted(15.Seconds()).ShouldBeTrue();
        }
Exemplo n.º 23
0
        static void Main()
        {
            //IContainer c = BootstrapContainer();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            NodeContext nc = null;

            NodeRecord rec        = new NodeRecord();
            string     host       = "localhost";
            bool       tryConnect = false;

            var connectForm = new ConnectForm();

            connectForm.FormClosing += (s, ea) =>
            {
                try
                {
                    rec.NodeId                 = connectForm.NodeId;
                    rec.OrgNodeId              = -1;
                    rec.QueueBaseName          = connectForm.AppName;
                    rec.QueueTransportSettings = TransportSettings.UseRabbitMq(connectForm.Host);


                    host       = connectForm.Host;
                    tryConnect = true;
                }
                catch (Exception ex)
                {
                    ea.Cancel = true;
                    MessageBox.Show(connectForm, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            };

            Application.Run(connectForm);


            if (connectForm.DialogResult != DialogResult.Cancel && tryConnect)
            {
                connectForm = null;

                var bus = ServiceBusFactory.New(sbc =>
                {
                    sbc.ReceiveFrom(rec.QueueUri);
                    sbc.UseControlBus();

                    rec.QueueTransportSettings.ApplyGlobalConfig(sbc);
                });

                // We got a node context, yay.
                // Launch a service which takes care of traffix, and provide some
                // means for the ClientForm to xommunixate with that service:
                var clientForm = new ClientForm(rec, bus);
                //LaunchMessageService(nc, svc =>
                //{
                Application.Run(clientForm);
                nc.Dispose();
                //});
            }
        }
        public SubscriptionServiceRegistry(IContainer container)
        {
            var configuration = container.GetInstance <IConfiguration>();

            For <ISessionFactory>()
            .Singleton()
            .Use(context => CreateSessionFactory());

            For(typeof(ISagaRepository <>))
            .Add(typeof(NHibernateSagaRepository <>));

            For <IServiceBus>()
            .Singleton()
            .Use(context =>
            {
                return(ServiceBusFactory.New(sbc =>
                {
                    sbc.ReceiveFrom(configuration.SubscriptionServiceUri);

                    sbc.UseMsmq();

                    sbc.SetConcurrentConsumerLimit(1);
                }));
            });
        }
Exemplo n.º 25
0
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            // in proc bus
            //var bus = new InProcessBus(container);
            //container.Register(Component.For<IBus>().Instance(bus));

            // for factory
            if (!container.Kernel.GetFacilities()
                .Any(x => x.GetType().Equals(typeof(TypedFactoryFacility))))
            {
                container.AddFacility <TypedFactoryFacility>();
            }

            // masstransit bus
            //var busAdapter = new MassTransitPublisher(bus);

            container.Register(
                Component.For <IServiceBus>()
                .UsingFactoryMethod(() => ServiceBusFactory.New(sbc =>
            {
                sbc.UseRabbitMq();
                sbc.ReceiveFrom(_EndpointUri);
                sbc.UseRabbitMqRouting();
                sbc.Subscribe(c => c.LoadFrom(container));
            })).LifeStyle.Singleton,
                Component.For <IBus>()
                .UsingFactoryMethod((k, c) =>
                                    new MassTransitPublisher(k.Resolve <IServiceBus>()))
                .Forward <IDispatchCommits>()
                .LifeStyle.Singleton);
        }
Exemplo n.º 26
0
            protected override void Load(ContainerBuilder builder)
            {
                // Register all consumers in this assembly
                builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                .Where(t => t.Implements <IConsumer>())
                .AsSelf();

                builder.Register(c => ServiceBusFactory.New
                                 (
                                     sbc =>
                {
                    sbc.UseMsmq(x =>
                    {
                        x.VerifyMsmqConfiguration();
                        x.UseMulticastSubscriptionClient();
                    });
                    sbc.ReceiveFrom(c.Resolve <IApplicationSettings>().MailSenderMessageQueueAddress);


                    // This will find all of the consumers in the container and register them with the bus.
                    // Resolve<ILifeTimeScope> is used to get all registrations from the container, the loadfrom method filters out all IConsumers and ISaga's
                    // Loadfrom is an extension method for autofac implemented in masstransit (Separate package: MassTransit.Autofac)
                    sbc.Subscribe(x => x.LoadFrom(c.Resolve <ILifetimeScope>()));
                }
                                 )
                                 )
                .As <IServiceBus>()
                .SingleInstance();
            }
        public void Should_publish_to_non_transactional_queue()
        {
            using (IServiceBus transactionalBus = ServiceBusFactory.New(x =>
            {
                x.UseMsmq();
                x.ReceiveFrom(_transactionalUri);
                x.UseMulticastSubscriptionClient();
                x.SetCreateMissingQueues(true);
                x.SetCreateTransactionalQueues(true);
            }))
            {
                using (IServiceBus nonTransactionalBus = ServiceBusFactory.New(x =>
                {
                    x.UseMsmq();
                    x.ReceiveFrom(_nonTransactionalUri);
                    x.UseMulticastSubscriptionClient();
                    x.SetCreateMissingQueues(true);
                    x.SetCreateTransactionalQueues(false);
                }))
                {
                    var future = new Future <MyMessage>();

                    nonTransactionalBus.SubscribeHandler <MyMessage>(future.Complete);

                    transactionalBus.ShouldHaveSubscriptionFor <MyMessage>();

                    transactionalBus.Publish(new MyMessage(),
                                             ctx => ctx.IfNoSubscribers(() => { throw new Exception("NoSubscribers"); }));

                    future.WaitUntilCompleted(8.Seconds()).ShouldBeTrue("The published message was not received>");
                }
            }
        }
Exemplo n.º 28
0
        public void OnlyReceiverShouldReceiveCommands()
        {
            const string receiverGuid = "af486b11-0fad-4f5a-98d3-7308ec925708";
            var          receiverId   = new Guid(receiverGuid);

            using (var serviceBus = ServiceBusFactory.New(bus =>
            {
                bus.ReceiveFrom(Config.CommandPublisherAddress);

                bus.UseRabbitMq();
            }))
                using (var handler1 = new TestCommandHandler(new Uri(Config.CommandHandlerAddress1), receiverId, "TestCommandHandler1", 5))
                    using (var handler2 = new TestCommandHandler(new Uri(Config.CommandHandlerAddress2), "TestCommandHandler2", 1))
                    {
                        serviceBus.SendTo(new TestCommand(), receiverId);
                        serviceBus.SendTo(new TestCommand(), receiverId);
                        serviceBus.SendTo(new TestCommand(), receiverId);
                        serviceBus.SendTo(new TestCommand(), receiverId);
                        serviceBus.SendTo(new TestCommand(), receiverId);

                        handler1.CommandReceived.WaitUntilCompleted(7.Seconds());

                        Assert.IsTrue(handler1.CommandReceived.IsCompleted && !handler2.CommandReceived.IsCompleted);
                    }
        }
Exemplo n.º 29
0
        private void Initialize(Action <IServiceBusConfigurator> busConfigureAction)
        {
            _publishSettings.Validate();

            if (_publishSettings.UsePublisherConfirms)
            {
                Action <IServiceBusConfigurator> publisherConfirmConfigureAction =
                    configurator =>
                {
                    busConfigureAction(configurator);
                    configurator.UsePublisherConfirms(_publishSettings);
                };
                _serviceBus = ServiceBusFactory.New(publisherConfirmConfigureAction);
            }
            else
            {
                _serviceBus = ServiceBusFactory.New(busConfigureAction);
            }

            _confirmer         = _publishSettings.Confirmer;
            _messageRepository = UnconfirmedMessageRepositoryFactory.Create(_publishSettings);

            _confirmer.PublicationFailed    += OnPublicationFailed;
            _confirmer.PublicationSucceeded += OnPublicationSucceeded;

            _lastMessageBufferStoreTimestamp = DateTime.UtcNow.Ticks;
            _lastPublishRetryTimestamp       = DateTime.UtcNow.Ticks;
            _checkOfflineTasksTimer          = new Timer(CheckOfflineTasks, null, _publishSettings.TimerCheckInterval, _publishSettings.TimerCheckInterval);
        }
Exemplo n.º 30
0
        public MessageSubscription[] GetMessageSubscriptions(ServerConfig3 server)
        {
            IViewSubscriptions sc = null;

            if (server.ServiceBus == _mgr.ServiceBusName &&
                server.ServiceBusVersion == _mgr.ServiceBusVersion &&
                server.ServiceBusQueueType == _mgr.MessageQueueType)
            {
                sc = _mgr as IViewSubscriptions;
            }
            else
            {
                var mgr = ServiceBusFactory.CreateManager(server.ServiceBus, server.ServiceBusVersion, server.ServiceBusQueueType);
                sc = mgr as IViewSubscriptions;
            }

            if (sc != null)
            {
                return(sc.GetMessageSubscriptions(server.ConnectionSettings, server.MonitorQueues.Select(q => q.Name)));
            }
            else
            {
                return(new MessageSubscription[0]);
            }
        }