安装包
MassTransit.Extensions.DependencyInjection
使用依赖注入容器生成总线
// 新建服务集合(DI容器)
IServiceCollection services = new ServiceCollection ();
services.AddMassTransit (config => {
// 向 DI 注入 UpdateCustomerConsumer 消费者
config.AddConsumer<UpdateCustomerConsumer> ();
// 添加总线
config.AddBus (service => {
// 创建基于内存的总线
var bus = Bus.Factory.CreateUsingInMemory (config => {
// 设置接收队列,队列名 test_queue
config.ReceiveEndpoint ("test_queue", ep => {
// 添加消费者
// 从 DI 中获取消费者
ep.ConfigureConsumer<UpdateCustomerConsumer> (service);
});
});
return bus;
});
});
var serviceProvicer = services.BuildServiceProvider ();
var bus = serviceProvicer.GetService<IBusControl> ();
bus.Start ();
bus.Publish (new YourMessage ()).Wait ();
Console.WriteLine ("Press any key to exit");
Console.ReadKey ();
bus.Stop ();