Come on, Winform uses dependency injection!

Come on, Winform uses dependency injection!

What is dependence injection? Dependency injection is a specific coding technique, and the most obvious one to me is to solve code coupling.

最后更新 4/22/2022 7:21 AM
AZRNG 鹏祥
预计阅读 4 分钟
分类
Winform
标签
.NET Winform dependency injection IOC

Webmaster: There are not many shared articles on Winform. This technology is relatively stable, and everything it needs is available. Today, I share the article on Winform Dependency Injection written by other accounts, hoping that friends who are doing related development can have new experiences.

1. introduced

What is dependence injection? Dependency injection is a specific coding technique, and the most obvious one to me is to solve code coupling.

2. objective

ASP.NET Core itself container container has been created, just need to add services to the container, but in Winform default or through the new way to operate (although I have upgraded to. Net6), recently in an open source project to increase their own features, and then I incidentally upgrade the original NetF to NetCore, and then want to use dependency injection to try.

C/S code written less, if there is wrong, trouble correction.

3. operation

Example environments in this article: VS 2022,. Net6, Windows Forms applications

4. ready

The example contains the following code

  • Forms: Form 1, Form 2

  • Service:IUserservice、Userservice、IOrderService、OrderService

public interface IUserservice
{
    string GetName();
}

public class UserService : IUserservice
{
    public string GetName()
    {
        return "IUserservice";
    }
}

public interface IOrderService
{
    string GetName();
}

public class OrderService : IOrderService
{
    public string GetName()
    {
        return "IOrderService";
    }
}

5. scene

In Form 1, IUserservice is injected through the constructor, and the IUserservice's name acquisition method is called in the Load event. After clicking the page button, Form 2 displays it. In Form 2, IOrderService is injected through dependency, and IOrderService's name acquisition method is called in the Load event. If you can operate multiple times without reporting an error, it is a success.

6. began

referencing assembly

<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0" />

Added an operation class for ServiceProviderHelper

public static class ServiceProviderHelper
{
    /// <summary>
    /// 全局服务提供者
    /// </summary>
    public static IServiceProvider ServiceProvider { get; private set; } = null!;

    /// <summary>
    /// 初始化构建ServiceProvider对象
    /// </summary>
    /// <param name="serviceProvider"></param>
    /// <exception cref="ArgumentNullException"></exception>
    public static void InitServiceProvider(ServiceProvider serviceProvider)
    {
        ArgumentNullException.ThrowIfNull(serviceProvider, nameof(serviceProvider));

        ServiceProvider = serviceProvider;
    }

    /// <summary>
    /// 获取Form服务
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    /// <exception cref="ArgumentException"></exception>
    public static Form GetFormService(Type type)
    {
        var service = ServiceProvider.GetRequiredService(type);
        if (service is Form fService)
        {
            return fService;
        }
        else
        {
            throw new ArgumentException($"{type.FullName} is not a Form");
        }
    }

    /// <summary>
    /// 获取Form服务
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    /// <exception cref="ArgumentException"></exception>
    public static T GetService<T>() where T : class
    {
        return ServiceProvider.GetRequiredService<T>();
    }
}

Modifying Program Method

internal static class Program
{
    /// <summary>
    ///  The main entry point for the application.
    /// </summary>
    [STAThread]
    private static void Main()
    {
        //.net6写法 之前是三行合一行
        ApplicationConfiguration.Initialize();

        //创建服务容器
        var services = new ServiceCollection();
        //添加服务注册
        ConfigureServices(services);

        //构建ServiceProvider对象
        ServiceProviderHelper.InitServiceProvider(services.BuildServiceProvider());

        //获取指定服务
        var main = ServiceProviderHelper.ServiceProvider.GetRequiredService<Form1>();
        Application.Run(main);
    }

    /// <summary>
    /// 注入服务
    /// </summary>
    /// <param name="services"></param>
    public static void ConfigureServices(IServiceCollection services)
    {
        //批量注入可以使用Scrutor或者自己封装
        services.AddScoped<IUserservice, UserService>();
        services.AddScoped<IOrderService, OrderService>();

        //其他的窗体也可以注入在此处
        services.AddSingleton(typeof(Form1));
        services.AddTransient(typeof(Form2));
    }
}

Inject on Form 1 and Form 2 respectively

private readonly IUserservice _userservice;

public Form1(IUserservice userservice)
{
    InitializeComponent();
    _userservice = userservice;
}

private readonly IOrderService _orderService;

public Form2(IOrderService orderService) : this()
{
    _orderService = orderService;
}

Click the Form 1 Form button to make the Form 2 form appear

private void button1_Click(object sender, EventArgs e)
{
    var form2 = ServiceProviderHelper.GetFormService(typeof(Form2));
    form2.Show();
}

After several normal operations, no abnormalities were found.

7. information

Implementation of dependency injection example based on Winform on. NET Core 3.1: http://www.example.com

Keep Exploring

延伸阅读

更多文章
同分类 / 同标签 2/29/2024

Data display can also be done in Winform

In the process of developing winform, data display functions are often needed. I have been using the gridcontrol before. Today, I want to use an example to introduce to you how to use the table component in ant design blazor hybrid to display data.

继续阅读
同分类 / 同标签 2/29/2024

Can Winform's interface become better?

A few days ago, I introduced to you the use of blazor hybrid in winform, and I also said that with blazor's ui, our winform program design can be more beautiful. Next, I want to use an example of drawing in winform blazor hybrid to illustrate it, hoping to be helpful to you.

继续阅读