How to use Autofac Dependency Injection in MassTransit IConsume

I am trying to use DI with my consumer class without success.

My consumer class:

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(); } } 

When I want to register a factory bus, the user must have a parameterless constructor.

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

Any help would be appreciated, I really don't know how to register my consumer ...

thanks

+5
source share
1 answer

Integration with Autofac is simple, there are extension methods in MassTransit.Autofac .

First, there is an AutofacConsumerFactory that will allow your consumers out of the container. You can add this to the container, or you can register it yourself using:

 builder.RegisterGeneric(typeof(AutofacConsumerFactory<>)) .WithParameter(new NamedParameter("name", "message")) .As(typeof(IConsumerFactory<>)); 

Then in the builder statement for the endpoint of the bus and the receiver:

 e.Consumer(() => context.Resolve<IConsumerFactory<TakeMeasureConsumer>()); 

Then you allow your consumers from the container.

Update:

For newer versions of MassTransit, add receive endpoints as follows:

 e.Consumer<TakeMeasureConsumer>(context); 
+8
source

Source: https://habr.com/ru/post/1232881/


All Articles