有没有办法注入(inject) IConsumer?
例如
public class UpdateCustomerConsumer : IConsumer<ITestMessage>
{
private IJimTest _jimTest;
public UpdateCustomerConsumer(IJimTest jimTest)
{
_jimTest = jimTest;
}
我已经使用 MassTransit.Extensions.DependencyInjection nuget 包设置了 Startup.ConfigureServices()。
services.AddMassTransit(x =>
{
x.AddBus(provider => Bus.Factory.CreateUsingRabbitMq(cfg =>
{
cfg.Host(new Uri("rabbitmq://localhost:5672/"), h => { });
cfg.ReceiveEndpoint("test", ep =>
{
ep.Consumer<Consumers.UpdateCustomerConsumer>();
});
cfg.ConfigureEndpoints(provider);
}));
});
services.AddSingleton<IJimTest, JimTest>();
但是 _jimTest 最终为空。
根据 documentation ,您的配置应如下所示:
services.AddMassTransit(x =>
{
x.AddConsumer<Consumers.UpdateCustomerConsumer>(); //added this line
x.AddBus(provider => Bus.Factory.CreateUsingRabbitMq(cfg =>
{
cfg.Host(new Uri("rabbitmq://localhost:5672/"), h => { });
cfg.ReceiveEndpoint("test", ep =>
{
ep.ConfigureConsumer<Consumers.UpdateCustomerConsumer>(provider); //changed
});
//if you use cfg.ReceiveEndpoint this one is not needed
//you can remove cfg.ReceiveEndpoint and use below instead
//cfg.ConfigureEndpoints(provider);
}));
});
services.AddSingleton<IJimTest, JimTest>();
我是一名优秀的程序员,十分优秀!