bflow1
bflow1

Reputation: 69

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.

Upvotes: 6

Views: 4493

Answers (3)

Random Person
Random Person

Reputation: 49

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
        }
    }
}

Upvotes: 0

Natrium
Natrium

Reputation: 31204

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();

Upvotes: 2

Farhad Zamani
Farhad Zamani

Reputation: 5861

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());

Upvotes: 14

Related Questions