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

时间:2015-10-04 04:53:32

标签: autofac masstransit

我正试图在我的消费者类中使用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>();
}

任何帮助将不胜感激,我真的不知道如何注册我的消费者...

由于

1 个答案:

答案 0 :(得分:11)

与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);
相关问题