Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using MediatR in a console application

Does anyone know how to implement MediatR in a console application, to call a handler function using the _mediatr.Send(obj) syntax. I'm using the .Net 6 framework. Thanks for the help.

like image 310
bflow1 Avatar asked Aug 28 '26 13:08

bflow1


2 Answers

First, you must install these packages:

  1. Microsoft.Extensions.DependencyInjection
  2. MediatR
  3. MediatR.Extensions.Microsoft.DependencyInjection

Then you can get IMediator from DI and use it.

using MediatR;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

var serviceCollection = new ServiceCollection()
    .AddMediatR(Assembly.GetExecutingAssembly())
    .BuildServiceProvider();

var mediator = serviceCollection.GetRequiredService<IMediator>();

//mediator.Send(new Command());
like image 109
Farhad Zamani Avatar answered Aug 30 '26 02:08

Farhad Zamani


This could be working in a console application in .NET 8 and MediatR 12.

HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);

builder.Services.AddTransient<IProcessingService, ProcessingService>(); // my own service where MediatR is injected
builder.Services.AddMediatR(cfg => {
    cfg.RegisterServicesFromAssembly(typeof(Program).Assembly);
});

using IHost host = builder.Build();

var processingService = host.Services.GetService<IProcessingService>();

processingService.Process();
like image 28
Natrium Avatar answered Aug 30 '26 02:08

Natrium



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!