EasynetQ AutoSubscriber setup for comsumers that need services injected

157 Views Asked by At

I'm trying to setup Auto Aubsciber within EasyNetQ/RabbitMQ using .Net7

This is what I have in my start up class:

var bus = RabbitHutch.CreateBus(ConnectionString);

builder.Services.AddSingleton(bus);

var subscriber = new AutoSubscriber(bus, "Test");

builder.Services.Subscribe(Assembly.GetExecutingAssembly().GetTypes());

I have a simple class to publish messages:

public class Test
{
    private readonly IBus _bus;

    public RabbitPublisher( IBus bus)
    {
        _bus = bus;
    }

    public async Task PublishAsync<T>(T messageContent)
    {
        await _bus.PubSub.PublishAsync(messageContent);
    }
}

And simple consumer class:

public class MessageConsumer : IConsumeAsync<Message>
{
    public MessageConsumer(ILogger logger)
    {
        ...
    }

    public async Task ConsumeAsync(Message message, CancellationToken cancellationToken = default) 
    {
      //Do work
    }
}

If I test this and publish a message I receive the following error:

Cannot dynamically create an instance of type 'MessageConsumer'. Reason: No parameterless constructor defined.

Now, if I create a parameterless contructor is works, but I need to inject services into this class. How can I achieve this?

I'm using .net 7 and EasynetQ version 7.5.

Thanks

1

There are 1 best solutions below

0
Minh On

This is what you missed due to AutoSubscriber config to work with MS DI

var subscriber = new AutoSubscriber(app.Services.GetRequiredService<IBus>(), "migration-status")
{
    AutoSubscriberMessageDispatcher = new DefaultAutoSubscriberMessageDispatcher(app.Services.GetRequiredService<IServiceResolver>())
};