gpt4 book ai didi

autofac - 如何在 MassTransit IConsume 中使用 Autofac 依赖注入(inject)

转载 作者:行者123 更新时间:2023-12-04 06:34:51 25 4
gpt4 key购买 nike

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

关于autofac - 如何在 MassTransit IConsume 中使用 Autofac 依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32930173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com