Using MediatR in a console application
Asked Answered
M

3

6

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.

Microfilm answered 25/7, 2022 at 6:21 Comment(0)
C
14

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());
Comatose answered 25/7, 2022 at 9:42 Comment(0)
S
2

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();
Salacious answered 12/12, 2023 at 19:46 Comment(0)
D
0

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
        }
    }
}
Dettmer answered 16/10 at 8:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.