WinForm使用IOC控制程序
1、添加Nuget包
Microsoft.Extensions.DependencyInjection
2、改变启动项
internal static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { //创建服务容器 var services = new ServiceCollection(); //添加服务注册 ConfigureServices(services); //先用DI容器生成 serviceProvider, 然后通过 serviceProvider 获取Main Form的注册实例 var serviceProvider = services.BuildServiceProvider(); var formMain = serviceProvider.GetRequiredService<MainForm>(); //主动从容器中获取FormMain实例, 这是简洁写法 // var formMain = (FormMain)serviceProvider.GetService(typeof(FormMain)); //更繁琐的写法 Application.Run(formMain); } /// <summary> /// 注入服务 /// </summary> /// <param name="services"></param> public static void ConfigureServices(IServiceCollection services) { services.AddSingleton<ILoginService, LoginService>(); services.AddScoped(typeof(MainForm)); } }
3、随便自定义一个接口和实现
public interface ILoginService { void Login(string username, string password); } public class LoginService : ILoginService { public void Login(string username, string password) { MessageBox.Show("登录成功!"); } }
4、构造方法注入
public partial class MainForm : Form { private readonly ILoginService _loginService; public MainForm(ILoginService loginService) { InitializeComponent(); _loginService = loginService; } private void button1_Click(object sender, EventArgs e) { _loginService.Login("uname","pwd"); } }