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.
Using MediatR in a console application
Asked Answered
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();
Install NuGet: Microsoft.Extensions.DependencyInjection
Install NuGet: MediatR
using MediatR;
using Microsoft.Extensions.DependencyInjection;
public class Program
{
public static async Task Main(string[] args)
{
var services = new ServiceCollection();
services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(Program).Assembly));
var sp = services.BuildServiceProvider();
using (var scope = sp.CreateScope())
{
var mediatr = scope.ServiceProvider.GetRequiredService<IMediator>();
// logic
}
}
}
© 2022 - 2024 — McMap. All rights reserved.