Search code examples
c#winforms.net-coredependency-injectionmediatr

How to use MediatR on Winform .net core


I have a .net core winform application and am implementing n-tier architecture(ApplicationLayer(winform), BLL, DAL)

Installed MediatR and MediatR.Extensions.Microsoft.DependencyInjection

I am currently following this site:

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

Where do I put this code

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

I have tried putting it on Main() like so:

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

and its giving me this error

Program does not contain a static 'Main' method suitable for an entry point


Solution

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

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

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

    2 - Change your Program.cs class 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 - Create your Command Response

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

    5 - Create 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 code

    enter image description here

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