我正在尝试将DI与我的消费者类一起使用而没有成功.
我的消费者阶层:
public class TakeMeasureConsumer : IConsumer<TakeMeasure> { private IUnitOfWorkAsync _uow; private IInstrumentOutputDomainService _instrumentOutputDomainService; public TakeMeasureConsumer(IUnitOfWorkAsync uow,IInstrumentOutputDomainService instrumentOutputDomainService) { _uow = uow; _instrumentOutputDomainService = instrumentOutputDomainService; } public async Task Consume(ConsumeContext<TakeMeasure> context) { var instrumentOutput = Mapper.Map<InstrumentOutput>(context.Message); _instrumentOutputDomainService.Insert(instrumentOutput); await _uow.SaveChangesAsync(); } }
protected override void Load(ContainerBuilder builder) { builder.Register(context => Bus.Factory.CreateUsingRabbitMq(cfg => { var host = cfg.Host(new Uri("rabbitmq://localhost/"),h => { h.Username("guest"); h.Password("guest"); }); cfg.ReceiveEndpoint(host,"intrument_take_measure",e => { // Must be a non abastract type with a parameterless constructor.... e.Consumer<TakeMeasureConsumer>(); }); })) .SingleInstance() .As<IBusControl>() .As<IBus>();
任何帮助将不胜感激,我真的不知道如何注册我的消费者……
谢谢
与Autofac集成很简单,MassTransit.Autofac包中有扩展方法可以提供帮助.
首先,有一个AutofacConsumerFactory将从容器中解析您的消费者.您可以将其添加到容器中,也可以使用以下命令自行注册:
builder.RegisterGeneric(typeof(AutofacConsumerFactory<>)) .WithParameter(new NamedParameter("name","message")) .As(typeof(IConsumerFactory<>));
然后,在总线和接收端点的构建器语句中:
e.Consumer(() => context.Resolve<IConsumerFactory<TakeMeasureConsumer>());
然后,这将从容器中解析您的消费者.
更新:
对于较新版本的MassTransit,添加如下接收端点:
e.Consumer<TakeMeasureConsumer>(context);