我之前发现了 MediatoR,它给我留下了深刻的印象,并且想知道如何将它添加到一个非常简单的 C# 控制台应用程序中。
实现此目的的一种老套且不完美的方法是在 CLI 应用程序项目中引用
Microsoft.Extensions.DependencyInjection
包,然后创建一个新的 ServiceCollection
,在此之后您可以添加中介器和您可能需要的所有其他服务。
var services = new ServiceCollection();
services.AddMediatR(/* config */);
// Dependency injection will not work perfectly, but inside of your classes, you could reference the IServiceProvider, instead of the services themself.
// For example:
class Dependency(IServiceProvider sp)
{
private IMediator mediator => sp.GetRequiredService<IMediator>;
public async Task Do(CancellationToken ct = default)
{
var request = new SomeRequest();
var resp = await mediator.Send(request, ct);
// do something with this.
}
}
您可以在我的项目中看到我如何将其用于不和谐机器人这里
我已经实现了 MediatoR,如下面的代码所示,我已经在 Program.cs 中编写了所有内容,但是您绝对可以创建单独的类
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);
}
}
}