Search code examples
c#console-application

Adding MediatoR into a C# Console Application


I previously discovered the MediatoR and I'm impressed by it and wondering how to add it to a very simple C# console application.


Solution

  • I have implemented the MediatoR as shown in the code below I have written everything in the Program.cs, however you definitely can create separate classes

    using System;
    using System.Diagnostics;
    using System.Reflection;
    using System.Threading;
    using System.Threading.Tasks;
    using MediatR;
    using Microsoft.Extensions.DependencyInjection;
    
    namespace ConsoleApp1
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var services = new ServiceCollection();
                ConfigureService(services);
                var serviceProvider = services.BuildServiceProvider();
                // Get MediatR instance
                var mediator = serviceProvider.GetRequiredService<IMediator>();
                var response = await mediator.Send(new Ping());
                for (int i = 0; i < response.Length; i++)
                {
                    Debug.WriteLine(response[i]);
    
                }
            }
    
            public static void ConfigureService(IServiceCollection services)
            {
                var mediator = services.AddMediatR(cfg => {
                    cfg.RegisterServicesFromAssembly(typeof(Program).Assembly);
                });
            }
    
        }
    
        public class Ping : IRequest<string[]>
        {
        }
    
        public class PingHandler : IRequestHandler<Ping, string[]>
        {
            public Task<string[]> Handle(Ping request, CancellationToken cancellationToken)
            {
                string[] cars = { "Volvo", "BMW", "Ford", "Mazda" };
                return Task.FromResult(cars);
            }
        }
    
    }