[ACCEPTED]-How to use MediatR on Winform .net core-mediatr

Accepted answer
Score: 10

The Main() method is the entry point of your application 14 and thus cannot be modified. As you were 13 adding a parameter to it, the compiler tells 12 that the it could not find the Main() (parameterless) method.

If 11 you want to work with dependency injection 10 + windows forms some additional steps are 9 needed.

1 - Install the package Microsoft.Extensions.DependencyInjection. Windows 8 Forms doesn't have DI capabilities natively 7 so we need do add it.

2 - Change your Program.cs class 6 to be like this

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 - Create your Command Request

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

4 5 - Create your Command Response

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

5 - Create 4 your Command Handler

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 implementation

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

Working 3 code

enter image description here

I'd never thought about using MediatR 2 along Windows Forms, it was a nice study 1 case. Nice question =)

More Related questions