加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在MassTransit IConsume中使用Autofac依赖注入

发布时间:2020-12-13 20:42:03 所属栏目:百科 来源:网络整理
导读:我正在尝试将DI与我的消费者类一起使用而没有成功. 我的消费者阶层: public class TakeMeasureConsumer : IConsumerTakeMeasure{ private IUnitOfWorkAsync _uow; private IInstrumentOutputDomainService _instrumentOutputDomainService; public TakeMeas
我正在尝试将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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读