如何在 Winform .net core 上使用 MediatR

How to use MediatR on Winform .net core

我有一个 .net 核心 winform 应用程序并且正在实现 n 层架构(ApplicationLayer(winform)、BLL、DAL)

已安装 MediatR 和 MediatR.Extensions.Microsoft.DependencyInjection

我目前正在关注这个网站:

https://dotnetcoretutorials.com/2019/04/30/the-mediator-pattern-part-3-mediatr-library/

我应该把这个代码放在哪里

public void ConfigureServices(IServiceCollection services)
{
    services.AddMediatR(Assembly.GetExecutingAssembly());
    //Other injected services. 
}

我试过像这样把它放在 Main() 上:

    static class Program
{
    /// <summary>
    ///  The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(IServiceCollection services)
    {
        services.AddMediatR(Assembly.GetExecutingAssembly());
        services.AddTransient<IApplicationHandler, ApplicationHandler>();

        Application.SetHighDpiMode(HighDpiMode.SystemAware);
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

它给我这个错误

程序不包含适合入口点的静态'Main'方法

Main() 方法是您的应用程序的入口点,因此无法修改。当您向它添加参数时,编译器告诉它找不到 Main()(无参数)方法。

如果您想使用依赖注入 + windows 表单,则需要一些额外的步骤。

1 - 安装包 Microsoft.Extensions.DependencyInjection。 Windows 表单本身没有 DI 功能,所以我们需要添加它。

2 - 将你的 Program.cs class 改成这样

static class Program
{
    /// <summary>
    ///  The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {

        Application.SetHighDpiMode(HighDpiMode.SystemAware);
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        // This class will contains your injections
        var services = new ServiceCollection();
       
        // Configures your injections
        ConfigureServices(services);

        // Service provider is the one that solves de dependecies
        // and give you the implementations
        using (ServiceProvider sp = services.BuildServiceProvider())
        {
            // Locates `Form1` in your DI container.
            var form1 = sp.GetRequiredService<Form1>();
            // Starts the application
            Application.Run(form1);
        }

    }

    // This method will be responsible to register your injections
    private static void ConfigureServices(IServiceCollection services)
    { 
        // Inject MediatR
        services.AddMediatR(Assembly.GetExecutingAssembly());
        
        // As you will not be able do to a `new Form1()` since it will 
        // contains your injected services, your form will have to be
        // provided by Dependency Injection.
        services.AddScoped<Form1>();

    }
}

3 - 创建您的命令请求

public class RetrieveInfoCommandRequest : IRequest<RetrieveInfoCommandResponse>
{
    public string Text { get; set; }
}

4 - 创建命令响应

public class RetrieveInfoCommandResponse
{
    public string OutputMessage { get; set; }
}

5 - 创建您的命令处理程序

public class RetrieveInfoCommandHandler : IRequestHandler<RetrieveInfoCommandRequest, RetrieveInfoCommandResponse>
{
    public async Task<RetrieveInfoCommandResponse> Handle(RetrieveInfoCommandRequest request, CancellationToken cancellationToken)
    {
        RetrieveInfoCommandResponse response = new RetrieveInfoCommandResponse();
        response.OutputMessage = $"This is an example of MediatR using {request.Text}";
        return response;
    }
}

6 - Form1 实施

public partial class Form1 : Form
{
    private readonly IMediator _mediator;
    public Form1(IMediator mediator)
    {
        _mediator = mediator;
        InitializeComponent();

    }

    private async void button1_Click(object sender, EventArgs e)
    {
        var outputMessage = await _mediator.Send(new RetrieveInfoCommandRequest
        {
            Text = "Windows Forms"
        });

        label1.Text = outputMessage.OutputMessage;
    }
}

工作代码

我从未想过在 Windows Forms 中使用 MediatR,这是一个很好的研究案例。好问题 =)