【问题标题】:How to use Autofac Dependency Injection in MassTransit IConsume如何在 MassTransit IConsume 中使用 Autofac 依赖注入
【发布时间】:2015-10-04 04:53:32
【问题描述】:

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


    【解决方案1】:

    与 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);
    

    【讨论】:

    • 嗨,克里斯,这对我有用。 masstransit.Autofac 包使它变得非常简单,而且 masstransit 很棒。谢谢!
    • Chris Patterson,您答案中的代码似乎不起作用。 context.Resolve - 但你注册了 IConsumerFactory。当我改变它时,我遇到了解决问题:Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'MassTransit.AutofacIntegration.AutofacConsumerFactory`1
    • 嗨,克里斯,很抱歉再次打扰您,但我现在在接收端点的构建器语句中收到此错误:类型 'AutofacConsumerFactory' 不能用作类型泛型类型或方法“ConsumerExtensions.Consumer(IReceiveEndpointConfigurator, Func, Action>)”中的参数“TConsumer”。没有从“MassTransit.AutofacIntegration.AutofacConsumerFactory”到“MassTransit.IConsumer”的隐式引用转换。
    • 我对以上内容进行了编辑,以确保其正确、有效且经过验证。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-02
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    相关资源
    最近更新 更多