Beispiel #1
0
        static void Main(string[] args)
        {
            var connection = new ConnectionConfiguration();

            connection.Port     = 5672;
            connection.UserName = "******";
            connection.Password = "******";

            connection.Hosts = new List <HostConfiguration> {
                new HostConfiguration()
                {
                    Host = @"rabbitmq", Port = 5672
                }
            };
            connection.ConnectIntervalAttempt = TimeSpan.FromSeconds(4);
            connection.RequestedHeartbeat     = 4;
            connection.Timeout = 20;
            var _bus = RabbitHutch.CreateBus(connection, ser => ser.Register <IEasyNetQLogger>(logger => new DoNothingLogger()));


            var subscriber = new AutoSubscriber(_bus, "#");

            subscriber.Subscribe(Assembly.GetExecutingAssembly());

            _bus.Respond <CheckUserPostPartOwner, CheckUserPostPartOwnerResponse>(request => new CheckUserPostPartOwnerResponse {
                IsOkay = new ResponseActions().IsUserOwnerPostpart(request.UserId, request.PostPartId)
            });
            _bus.Respond <CheckUserCollectionOwner, CheckUserCollectionOwnerResponse>(request => new CheckUserCollectionOwnerResponse {
                IsOkay = new ResponseActions().IsUserOwnerPostCollection(request.UserId, request.CollectionId)
            });

            Console.WriteLine("Main API Eventhandler Listening");
            string typed = Console.ReadLine();
        }
    public static IApplicationBuilder UseRabbitMq(this IApplicationBuilder applicationBuilder,
                                                  string subscriptionIdPrefix = null, Assembly consumerAssembly = null)
    {
        consumerAssembly ??= Assembly.GetEntryAssembly();

        if (consumerAssembly is null)
        {
            throw new ArgumentNullException(nameof(consumerAssembly));
        }

        var services = applicationBuilder.ApplicationServices;

        var lifeTime           = services.GetService <IApplicationLifetime>();
        var rabbitMqConnection = services.GetService <IRabbitMqConnection>();

        lifeTime.ApplicationStarted.Register(() =>
        {
            var subscriber = new AutoSubscriber(rabbitMqConnection.Bus, subscriptionIdPrefix)
            {
                AutoSubscriberMessageDispatcher =
                    new MicrosoftDependencyInjectionMessageDispatcher(applicationBuilder.ApplicationServices)
            };

            subscriber.Subscribe(new[] { consumerAssembly });
            subscriber.SubscribeAsync(new[] { consumerAssembly });
        });

        lifeTime.ApplicationStopped.Register(() => rabbitMqConnection.Bus.Dispose());

        return(applicationBuilder);
    }
Beispiel #3
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            var services = app.ApplicationServices.CreateScope().ServiceProvider;

            var lifeTime = services.GetService <Microsoft.Extensions.Hosting.IHostApplicationLifetime>();
            var bus      = services.GetService <IBus>();

            lifeTime.ApplicationStarted.Register(() =>
            {
                var subscriber = new AutoSubscriber(bus, "OrderService1");
                subscriber.Subscribe(Assembly.GetExecutingAssembly());
                subscriber.SubscribeAsync(Assembly.GetExecutingAssembly());
            });

            lifeTime.ApplicationStopped.Register(() => { bus.Dispose(); });
            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
        public When_autosubscribing_with_subscription_configuration_action()
        {
            pubSub = Substitute.For <IPubSub>();
            bus    = Substitute.For <IBus>();
            bus.PubSub.Returns(pubSub);

            var autoSubscriber = new AutoSubscriber(bus, "my_app")
            {
                ConfigureSubscriptionConfiguration =
                    c => c.WithAutoDelete()
                    .WithExpires(10)
                    .WithPrefetchCount(10)
                    .WithPriority(10)
            };

            pubSub.SubscribeAsync(
                Arg.Is("MyActionTest"),
                Arg.Any <Func <MessageA, CancellationToken, Task> >(),
                Arg.Any <Action <ISubscriptionConfiguration> >()
                )
            .Returns(Task.FromResult(Substitute.For <ISubscriptionResult>()).ToAwaitableDisposable())
            .AndDoes(a => capturedAction = (Action <ISubscriptionConfiguration>)a.Args()[2]);

            autoSubscriber.Subscribe(new[] { typeof(MyConsumerWithAction) });
        }
Beispiel #5
0
 public RabbitHostedService(ILogger <RabbitHostedService> logger, IServiceScopeFactory serviceScopeFactory, IBus bus, IQueueResponseService responseService)
     : base(logger, serviceScopeFactory)
 {
     _bus             = bus;
     _responseService = responseService;
     _subscriber      = new AutoSubscriber(_bus, Assembly.GetExecutingAssembly().GetName().Name);
 }
        public void Should_be_able_to_autosubscribe_to_several_messages_in_one_consumer()
        {
            var interceptedSubscriptions = new List <Tuple <string, Delegate> >();
            var busFake = new BusFake
            {
                InterceptSubscribe = (s, a) => interceptedSubscriptions.Add(new Tuple <string, Delegate>(s, a))
            };
            var autoSubscriber = new AutoSubscriber(busFake, "MyAppPrefix");

            autoSubscriber.Subscribe(GetType().Assembly);

            interceptedSubscriptions.Count.ShouldEqual(4);
            interceptedSubscriptions.TrueForAll(i => i.Item2.Method.DeclaringType == typeof(DefaultMessageDispatcher)).ShouldBeTrue();

            CheckSubscriptionsContains <MessageA>(interceptedSubscriptions, "MyAppPrefix:e8afeaac27aeba31a42dea8e4d05308e");
            CheckSubscriptionsContains <MessageB>(interceptedSubscriptions, "MyExplicitId");
            CheckSubscriptionsContains <MessageC>(interceptedSubscriptions, "MyAppPrefix:cf5f54ed13478763e2da2bb3c9487baa");

            var messageADispatcher = (Action <MessageA>)interceptedSubscriptions.Single(x => x.Item2.GetType().GetGenericArguments()[0] == typeof(MessageA)).Item2;
            var message            = new MessageA {
                Text = "Hello World"
            };

            messageADispatcher(message);
        }
        public When_autosubscribing_with_subscription_configuration_action_and_attribute()
        {
            bus = Substitute.For <IBus>();

            var autoSubscriber = new AutoSubscriber(bus, "my_app")
            {
                ConfigureSubscriptionConfiguration =
                    c => c.WithAutoDelete(false)
                    .WithExpires(11)
                    .WithPrefetchCount(11)
                    .WithPriority(11)
            };

            bus.When(x => x.Subscribe(
                         Arg.Is("MyActionAndAttributeTest"),
                         Arg.Any <Action <MessageA> >(),
                         Arg.Any <Action <ISubscriptionConfiguration> >()
                         ))
            .Do(a =>
            {
                capturedAction = (Action <ISubscriptionConfiguration>)a.Args()[2];
            });

            autoSubscriber.Subscribe(GetType().GetTypeInfo().Assembly);
        }
        public IBus CreateConsumerBus(string connectionStringKey, ConsumerRegistration consumers)
        {
            var appSettings = new AppSettings();
            var connectionString = appSettings.ConnectionStrings.Get(connectionStringKey, () => DefaultConnection);
            var subscriptionPrefix = appSettings.RabbitMQ.SubscriptionPrefix;

            try
            {
                var bus = CreateBus(connectionStringKey, null);

                var dispatcher = new NoMagicAutoDispatcher(consumers);
                var autoSubscriber = new AutoSubscriber(bus, subscriptionPrefix)
                                     {
                                         AutoSubscriberMessageDispatcher = dispatcher
                                     };

                var consumerAssemblies = consumers.GetAssemblies();
                autoSubscriber.Subscribe(consumerAssemblies);
                

                Log.DebugFormat("Connected to RabbitMQ on {0} and using subscription prefix {1}", connectionString, subscriptionPrefix);

                return bus;
            }
            catch (Exception e)
            {
                Log.ErrorFormat("Failed to create a bus for RabbitMQ with connectionstring: {0}", connectionString);
                Log.ErrorFormat("The failure was {0}", e.Message);

                throw;
            }
        }
Beispiel #9
0
        public static IApplicationBuilder UseSubscriber(this IApplicationBuilder app, string prefix,
                                                        params Assembly[] assembly)
        {
            var services = app.ApplicationServices.CreateScope().ServiceProvider;

            var lifetime = services.GetService <IApplicationLifetime>();
            var bus      = services.GetService <IBus>();

            lifetime.ApplicationStarted.Register(() =>
            {
                if (bus != null)
                {
                    var subscriber = new AutoSubscriber(bus, prefix)
                    {
                        AutoSubscriberMessageDispatcher = new MessageDispatcher(app.ApplicationServices)
                    };
                    subscriber.Subscribe(assembly);
                    subscriber.SubscribeAsync(assembly);
                }
            });

            lifetime.ApplicationStopped.Register(() => bus.Dispose());

            return(app);
        }
Beispiel #10
0
        public void SetUp()
        {
            bus = RabbitHutch.CreateBus("host=localhost");
            var subscriber = new AutoSubscriber(bus, "autosub.integration");

            subscriber.Subscribe(Assembly.GetExecutingAssembly());
        }
Beispiel #11
0
        public static void Main(string[] args)
        {
            var connStr = "host=127.0.0.1;virtualHost=wangyunfei;username=admin;password=admin";


            /*
             * 过IBus实例去订阅消息(这里是除非用户关闭程序否则一直处于监听状态),
             * 当发布者发布了指定类型的消息之后,这里就把它打印出来(红色字体显示)。
             */
            using (var bus = RabbitHutch.CreateBus(connStr))
            {
                //This is something you only should do ONCE, preferably on application start up.
                AutoSubscriber autoSubscriber = new AutoSubscriber(bus, "WYF");
                //autoSubscriber.Subscribe(Assembly.GetExecutingAssembly());

                //简单订阅方式
                //bus.Subscribe<OrderMessage>("my_test_subscriptionid", HandleTextMessage);

                //自定义消费者 ps:为什么用Assembly.GetExecutingAssembly()创建不到队列?
                autoSubscriber.SubscribeAsync(typeof(SendOrderEmailToUserConsumer).Assembly);

                Console.WriteLine("Listening for messages. Hit <return> to quit.");
                Console.ReadLine();
            }
        }
        public void ShouldResolveConsumerFromContainer()
        {
            // create the container
            var container = new WindsorContainer();

            // register our consumer
            container.Register(
                Component.For <MyConsumer>().ImplementedBy <MyConsumer>()
                );

            var bus = RabbitHutch.CreateBus("host=localhost");

            // setup the AutoSubscriber
            var autoSubscriber = new AutoSubscriber(bus, "My_subscription_id_prefix")
            {
                MessageDispatcher = new WindsorMessageDispatcher(container)
            };

            autoSubscriber.Subscribe(GetType().Assembly);

            using (var channel = bus.OpenPublishChannel())
            {
                channel.Publish(new MessageA {
                    Text = "Hello World!"
                });
            }

            Thread.Sleep(1000);
        }
Beispiel #13
0
        static void Main(string[] args)
        {
            string rabbitMQBrokerHost = "localhost";
            string virtualHost        = "command-pipeline";
            string username           = Settings.Default.UserName;
            string password           = Settings.Default.Password;

            string connectionString = string.Format(
                "host={0};virtualHost={1};username={2};password={3}",
                rabbitMQBrokerHost, virtualHost, username, password);

            Console.WriteLine("Connect: " + connectionString);
            using (var bus = RabbitHutch.CreateBus(connectionString))
            {
                Console.WriteLine("Start...");

                bus.Subscribe <BuildCommand>(username, command =>
                {
                    Console.WriteLine(command.RepositoryProviderName + ", " + command.RepositoryUri);
                },
                                             x => x.WithTopic(username));

                var subscriber = new AutoSubscriber(bus, username);

                subscriber.Subscribe(Assembly.GetExecutingAssembly());

                Console.WriteLine("Press any key to quit.");
                Console.ReadLine();
            }
        }
Beispiel #14
0
        public void Should_be_able_to_take_control_of_subscription_id_generation()
        {
            var interceptedSubscriptions = new List <Tuple <string, Delegate> >();
            var busFake = new BusFake
            {
                InterceptSubscribe = (s, a) => interceptedSubscriptions.Add(new Tuple <string, Delegate>(s, a))
            };
            var fixedSubscriptionIds = new[] { "2f481170-8bc4-4d0f-a972-bd45191b1706", "be4ac633-ea29-4ed0-a0bf-419a01a0e9d4" };
            var callCount            = 0;
            var autoSubscriber       = new AutoSubscriber(busFake, "MyAppPrefix")
            {
                GenerateSubscriptionId = c => fixedSubscriptionIds[callCount++]
            };

            autoSubscriber.Subscribe(GetType().Assembly);

            interceptedSubscriptions.Count.ShouldEqual(3);
            interceptedSubscriptions[0].Item1.ShouldEqual(fixedSubscriptionIds[0]);
            interceptedSubscriptions[0].Item2.Method.GetParameters()[0].ParameterType.ShouldEqual(typeof(MessageA));

            interceptedSubscriptions[1].Item1.ShouldEqual("MyExplicitId");
            interceptedSubscriptions[1].Item2.Method.GetParameters()[0].ParameterType.ShouldEqual(typeof(MessageB));

            interceptedSubscriptions[2].Item1.ShouldEqual(fixedSubscriptionIds[1]);
            interceptedSubscriptions[2].Item2.Method.GetParameters()[0].ParameterType.ShouldEqual(typeof(MessageC));
        }
Beispiel #15
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();

            services.AddSingleton(RabbitHutch.CreateBus(Configuration.GetConnectionString("RabbitMQ")));

            services.AddSingleton <MessageDispatcher>();

            services.AddSingleton <IEmailSender>(
                x => new EmailSender(
                    Configuration.GetSection("SendersSettings").GetSection("email").Value,
                    Configuration.GetSection("SendersSettings").GetSection("password").Value)
                );

            services.AddScoped <EmailSendingConsumer>();

            services.AddSingleton(provider =>
            {
                var subscriber = new AutoSubscriber(provider.GetRequiredService <IBus>(), "EmailSenderService")
                {
                    AutoSubscriberMessageDispatcher    = provider.GetRequiredService <MessageDispatcher>(),
                    ConfigureSubscriptionConfiguration = new System.
                                                         Action <ISubscriptionConfiguration>(c => c.WithQueueName("EmailSenderService"))
                };

                return(subscriber);
            });
        }
        public AutoSubscriberIntegrationTests()
        {
            bus = RabbitHutch.CreateBus("host=localhost");
            var subscriber = new AutoSubscriber(bus, "autosub.integration");

            subscriber.Subscribe(GetType().GetTypeInfo().Assembly);
        }
Beispiel #17
0
        public void Should_be_able_to_autosubscribe_with_async_to_several_messages_in_one_consumer()
        {
            var interceptedSubscriptions = new List <Tuple <string, Delegate> >();
            var busFake = new BusFake
            {
                InterceptSubscribe = (s, a) => interceptedSubscriptions.Add(new Tuple <string, Delegate>(s, a))
            };
            var autoSubscriber = new AutoSubscriber(busFake, "MyAppPrefix");

            autoSubscriber.SubscribeAsync(GetType().Assembly);

            interceptedSubscriptions.Count.ShouldEqual(3);
            interceptedSubscriptions.TrueForAll(i => i.Item2.Method.DeclaringType == typeof(DefaultAutoSubscriberMessageDispatcher)).ShouldBeTrue();

            CheckSubscriptionsContains <MessageA>(interceptedSubscriptions, "MyAppPrefix:595a495413330ce1a7d03dd6a434b599");
            CheckSubscriptionsContains <MessageB>(interceptedSubscriptions, "MyExplicitId");
            CheckSubscriptionsContains <MessageC>(interceptedSubscriptions, "MyAppPrefix:e65118ba1611619fa7afb53dc916866e");

            var messageADispatcher = (Func <MessageA, Task>)interceptedSubscriptions.Single(x => x.Item2.GetType().GetGenericArguments()[0] == typeof(MessageA)).Item2;
            var message            = new MessageA {
                Text = "Hello World"
            };

            messageADispatcher(message);
            MyAsyncConsumer.MessageAText.ShouldEqual("Hello World");
        }
Beispiel #18
0
        public void SetUp()
        {
            bus = MockRepository.GenerateMock <IBus>();

            var autoSubscriber = new AutoSubscriber(bus, "my_app")
            {
                ConfigureSubscriptionConfiguration =
                    c => c.WithAutoDelete(false)
                    .WithCancelOnHaFailover(false)
                    .WithExpires(11)
                    .WithPrefetchCount(11)
                    .WithPriority(11)
            };

            bus.Stub(x => x.Subscribe(
                         Arg <string> .Is.Equal("MyActionAndAttributeTest"),
                         Arg <Action <MessageA> > .Is.Anything,
                         Arg <Action <ISubscriptionConfiguration> > .Is.Anything
                         ))
            .WhenCalled(a =>
            {
                capturedAction = (Action <ISubscriptionConfiguration>)a.Arguments[2];
            });

            autoSubscriber.Subscribe(GetType().Assembly);
        }
Beispiel #19
0
        static void Main(string[] args)
        {
            var connection = new ConnectionConfiguration();

            connection.Port     = 5672;
            connection.UserName = "******";
            connection.Password = "******";

            connection.Hosts = new List <HostConfiguration> {
                new HostConfiguration()
                {
                    Host = @"rabbitmq", Port = 5672
                }
            };
            connection.ConnectIntervalAttempt = TimeSpan.FromSeconds(4);
            connection.RequestedHeartbeat     = 4;
            connection.Timeout = 20;
            var _bus = RabbitHutch.CreateBus(connection, ser => ser.Register <IEasyNetQLogger>(logger => new DoNothingLogger()));


            var subscriber = new AutoSubscriber(_bus, "#");

            subscriber.Subscribe(Assembly.GetExecutingAssembly());
            Console.WriteLine("Identity EventHandler Listening");
            string typed = Console.ReadLine();
        }
        public When_autosubscribing_async()
        {
            //mockBuilder = new MockBuilder();
            mockBuilder = new MockBuilder();

            var autoSubscriber = new AutoSubscriber(bus: mockBuilder.Bus, subscriptionIdPrefix: "my_app");

            autoSubscriber.SubscribeAsync(typeof(MyAsyncConsumer));
        }
        public void SetUp()
        {
            mockBuilder = new MockBuilder();
//            mockBuilder = new MockBuilder(x => x.Register<IEasyNetQLogger, ConsoleLogger>());

            var autoSubscriber = new AutoSubscriber(mockBuilder.Bus, "my_app");

            autoSubscriber.Subscribe(typeof(MyAsyncConsumer), typeof(MyConsumer), typeof(MyGenericAbstractConsumer <>));
        }
Beispiel #22
0
        public void SetUp()
        {
            mockBuilder = new MockBuilder();
//            mockBuilder = new MockBuilder(x => x.Register<IEasyNetQLogger, ConsoleLogger>());

            var autoSubscriber = new AutoSubscriber(mockBuilder.Bus, "my_app");

            autoSubscriber.Subscribe(GetType().Assembly);
        }
        public When_autosubscribing_with_explicit_implementation()
        {
            //mockBuilder = new MockBuilder();
            mockBuilder = new MockBuilder();

            var autoSubscriber = new AutoSubscriber(mockBuilder.Bus, "my_app");

            autoSubscriber.Subscribe(new[] { typeof(MyConsumer), typeof(MyGenericAbstractConsumer <>) });
        }
Beispiel #24
0
        public When_autosubscribing_async()
        {
            //mockBuilder = new MockBuilder();
            mockBuilder = new MockBuilder();

            var autoSubscriber = new AutoSubscriber(mockBuilder.Bus, "my_app");

            autoSubscriber.Subscribe(new[] { typeof(MyAsyncConsumer) });
        }
        public When_autosubscribing_with_assembly_scanning()
        {
            mockBuilder = new MockBuilder();
//            mockBuilder = new MockBuilder(x => x.Register<IEasyNetQLogger, ConsoleLogger>());

            var autoSubscriber = new AutoSubscriber(mockBuilder.Bus, "my_app");

            autoSubscriber.Subscribe(GetType().GetTypeInfo().Assembly);
        }
        public When_autosubscribing_with_explicit_implementation()
        {
            //mockBuilder = new MockBuilder();
            mockBuilder = new MockBuilder();

            var autoSubscriber = new AutoSubscriber(mockBuilder.Bus, "my_app");

            parameters = new Dictionary <string, object>();
            autoSubscriber.Subscribe(typeof(MyConsumer), typeof(MyGenericAbstractConsumer <>));
        }
Beispiel #27
0
        /// <summary>
        /// 自动订阅
        /// </summary>
        /// <param name="assemblyName"></param>
        /// <param name="subscriptionIdPrefix"></param>
        /// <param name="topic"></param>
        /// <returns>Task</returns>
        public async Task AutoSubscribeAsync(string assemblyName, string subscriptionIdPrefix, string topic)
        {
            var subscriber = new AutoSubscriber(bus, subscriptionIdPrefix);

            if (!string.IsNullOrEmpty(topic))
            {
                subscriber.ConfigureSubscriptionConfiguration = x => x.WithTopic(topic);
            }
            await Task.Run(() => subscriber.SubscribeAsync(Assembly.Load(assemblyName)));
        }
Beispiel #28
0
        /// <summary>
        /// 自动订阅
        /// </summary>
        /// <param name="assemblyName"></param>
        /// <param name="subscriptionIdPrefix"></param>
        /// <param name="topic"></param>
        public void AutoSubscribe(string assemblyName, string subscriptionIdPrefix, string topic)
        {
            var subscriber = new AutoSubscriber(bus, subscriptionIdPrefix);

            if (!string.IsNullOrEmpty(topic))
            {
                subscriber.ConfigureSubscriptionConfiguration = x => x.WithTopic(topic);
            }
            subscriber.Subscribe(Assembly.Load(assemblyName));
        }
Beispiel #29
0
        // https://github.com/EasyNetQ/EasyNetQ/wiki/Auto-Subscriber
        private static void SubscribeHandlers(IBus bus, IServiceProvider services)
        {
            var dispatcherLogger = services.GetRequiredService <ILogger <MessageDispatcher> >();
            var subscriber       = new AutoSubscriber(bus, "auto")
            {
                AutoSubscriberMessageDispatcher = new MessageDispatcher(services, dispatcherLogger),
            };

            subscriber.SubscribeAsync(Assembly.GetExecutingAssembly());
        }
        /// <summary>
        /// Scans the current directory for defined easynetq subscribers.
        /// </summary>
        /// <param name="bus">The easynetq rabbitmq bus instance.</param>
        /// <param name="assemblies">The list of assemblies containeg subscriber classes.</param>
        /// <param name="container">The injection container for adding the subscribers.</param>
        private static void ScanForSubscribers(IBus bus, IEnumerable <Assembly> assemblies, IKernel container)
        {
            // Load all publish/subscribe subscribers
            var subscriberScanner = new AutoSubscriber(bus, ConfigurationExtensions.ApplicationSetting("Rabbit.ServiceName").Replace(" ", "_"))
            {
                AutoSubscriberMessageDispatcher = new NinjectAutoSubscriberMessageDispatcher(container)
            };

            subscriberScanner.Subscribe(assemblies.ToArray());
        }
        public When_autosubscribing()
        {
            mockBuilder = new MockBuilder();
//            mockBuilder = new MockBuilder(x => x.Register<IEasyNetQLogger, ConsoleLogger>());

            var autoSubscriber = new AutoSubscriber(mockBuilder.Bus, "my_app");

            parameters = new Dictionary <string, object>();
            autoSubscriber.Subscribe(typeof(MyAsyncConsumer), typeof(MyConsumer), typeof(MyGenericAbstractConsumer <>));
        }
        public void Start()
        {
            //todo move strings to configs
            _container.Register(Classes.FromThisAssembly().BasedOn(typeof(IConsume<>)).WithServiceSelf());

            var autoSubscriber = new AutoSubscriber(_bus, "My_subscription_id_prefix")
            {
                AutoSubscriberMessageDispatcher = new WindsorMessageDispatcher(_container, _logger)
            };

            autoSubscriber.Subscribe(Assembly.GetExecutingAssembly());
        }
Beispiel #33
0
        // ReSharper disable once UnusedParameter.Local
        private static void Main(string[] args)
        {
            LoggerConfig.ConfigureLogger();
            var container = UnityConfig.RegisterComponents();

            RabbitHutch.SetContainerFactory(() => new UnityAdapter(container));

            using (var bus = RabbitHutch.CreateBus(ConfigurationManager.ConnectionStrings["RabbitMQ"].ConnectionString))
            {
                var autoSubscriber = new AutoSubscriber(bus, "Worker")
                {
                    AutoSubscriberMessageDispatcher = new UnityMessageDispatcher(container)
                };

                autoSubscriber.Subscribe(Assembly.GetExecutingAssembly());
                autoSubscriber.SubscribeAsync(Assembly.GetExecutingAssembly());

                Console.ReadLine();
            }
        }
Beispiel #34
0
        public bool Start()
        {
            Log.Info("ApiPushService starting");

            var bus = RabbitHutch.CreateBus(_configuration.RabbitMqConnectionString, register => register.Register<IEasyNetQLogger>(_ => new EasyNetQLogger()));

            var subscriber = new AutoSubscriber(bus, "name")
            {
                ConfigureSubscriptionConfiguration = c =>
                {
                    c.WithPrefetchCount(_configuration.PrefetchCount);
                    c.WithAutoDelete(_configuration.AutoDelete);
                },
                GenerateSubscriptionId = info => info.ConcreteType.FullName,
                AutoSubscriberMessageDispatcher = _dispatcher
            };

            subscriber.Subscribe(Assembly.GetExecutingAssembly());

            Log.Info("ApiPushService started");
            return true;
        }
        public IBus CreateBus(string connectionStringKey, IWindsorContainer container)
        {
            var appSettings = new AppSettings();
            var connectionString = appSettings.ConnectionStrings.Get(connectionStringKey, () => DefaultConnection);
            var subscriptionPrefix = appSettings.RabbitMQ.SubscriptionPrefix;

            try
            {

                Log.InfoFormat("Connecting to RabbitMQ via {0} and using subscription prefix {1}", connectionString, subscriptionPrefix);

                var logger = new RabbitMQLogger();

                var bus = RabbitHutch.CreateBus(connectionString, x => x.Register<IEasyNetQLogger>(p => logger));
                var autoSubscriber = new AutoSubscriber(bus, subscriptionPrefix)
                {
                    AutoSubscriberMessageDispatcher = new WindsorMessageDispatcher(container)
                };

                var registration = new ConsumerRegistration();
                var assemblies = registration.GetAssemblies(container);

                autoSubscriber.Subscribe(assemblies.ToArray());
                autoSubscriber.SubscribeAsync(assemblies.ToArray());

                Log.DebugFormat("Connected to RabbitMQ on {0} and using subscription prefix {1}", connectionString, subscriptionPrefix);

                return bus;
            }
            catch (Exception e)
            {
                Log.ErrorFormat("Failed to create a bus for RabbitMQ with connectionstring: {0}", connectionString);
                Log.ErrorFormat("The failure was {0}", e.Message);

                throw;
            }
        }