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.
First, you must install these packages:
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());
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With