I'm 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 the bus factory the consumer 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
Integrating with Autofac is easy, there are extension methods in the MassTransit.Autofac
package that help out.
First, there is an AutofacConsumerFactory
that will resolve your consumers from 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 bus and receive endpoint:
e.Consumer(() => context.Resolve<IConsumerFactory<TakeMeasureConsumer>());
This will then resolve your consumers from the container.
Update:
For newer versions of MassTransit add receive endpoints like this:
e.Consumer<TakeMeasureConsumer>(context);