jjnrmason
jjnrmason

Reputation: 311

Mass transit consumer dependency injection

I have a dotnet core console application and wish to inject a class into a consumer. I have my receive endpoint setup here with a single consumer.

sbc.ReceiveEndpoint(appSettings.QueueUrl, ep => {
    ep.Consumer<AddAchievementConsumer>();
});

I then have my consumer class here.

public class AddAchievementConsumer : IConsumer<AddAchievementQueueMessage> {

        private readonly IRepository repository;
        private readonly IAchievementFactory achievementFactory;

        public AddAchievementConsumer(IRepository repository, IAchievementFactory achievementFactory) {
            this.repository = repository;
            this.achievementFactory = achievementFactory;
        }

        public Task Consume(ConsumeContext<AddAchievementQueueMessage> context) {
            var achievementService = new AchievementManagementService(this.repository, this.achievementFactory);
            achievementService.CreateAchievement(context.Message.Title, context.Message.Description, context.Message.Points);
 
            return Task.CompletedTask;
        }

    }

I want to be able to inject IRepository and IAchievementFactory into the consumer using dependency injection. Now I'm aware on the endpoint I could go:

ep.Consumer(() => new AddAchievementConsumer(repository, achievementFactory));

Now that would be fine but I wish to be able to use the depenency injection to inject them on their own without having to do it myself as in the future there will be multiple consumers.

Could anyone help? Thanks.

Upvotes: 2

Views: 4641

Answers (2)

Shareef U Din
Shareef U Din

Reputation: 1

You can use it like

e.ConfigureConsumer<YouEventConsumer>(context);

Upvotes: 0

Chris Patterson
Chris Patterson

Reputation: 33278

If you refer to the documentation there are many examples of how to configure MassTransit using the .NET Core Generic host, dependency injection, etc.

Upvotes: 4

Related Questions