本文主要内容参考自下面几篇博客,操作步骤只是为了做个备注方便回忆,具体细节和原理还是推荐大家自行阅读下面几篇博客:
- Dependency Injection in Windows Form or WPF Application .NET Core
- Dependency Injection in .NET Core Console app using Generic HostBuilder
- Loading Configuration (.INI,.XML,.JSON) in .NET Core Console or WinForm application – Part I
操作步骤
我的目标是在 .NET Core 3.1 WinForm 中注入官方自带的 Configuration、Logger 和 EF Core。
- 新建 .NET Core 3.1 WinForm 项目
- NuGet 安装 Microsoft.Extensions.Hosting
配置 EF Core(这步可以参考官方的 ASP.NET Core 教程)
- NuGet 安装 EF Core 相关包
- 创建实体类
创建 DbContext
public class K3DbContext : DbContext{public K3DbContext(DbContextOptions<K3DbContext> options) : base(options){}public DbSet<XX> XXs { get; set; }}
手动添加 appsettings.json 文件,并将其设置为总是复制到输出目录
{"Logging": {"LogLevel": {"Default": "Information"}},"AllowedHosts": "*","ConnectionStrings": {"K3Connection": "server=10.XX.XX.XXX;Database=K3;User ID=XX;Password=XX"}}
修改 Main() 代码
[STAThread]static void Main(){Application.SetHighDpiMode(HighDpiMode.SystemAware);Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);// CreateDefaultBuilder 里面自动注入并配置了 IConfigurationvar hostBuilder = Host.CreateDefaultBuilder().ConfigureServices((hostContext, services) =>{services.AddLogging(configure => configure.AddDebug());services.AddTransient<Form1>();services.AddDbContext<K3DbContext>(options =>options.UseSqlServer(hostContext.Configuration.GetConnectionString("K3Connection")));});var builderDefault = hostBuilder.Build();using (var serviceScope = builderDefault.Services.CreateScope()){var services = serviceScope.ServiceProvider;var form1 = services.GetRequiredService<Form1>();Application.Run(form1);}}
在 Form1 中使用注入的实例
public partial class Form1 : Form{private readonly IConfiguration _configuration;private readonly ILogger<Form1> _logger;public Form1(IConfiguration configuration, ILogger<Form1> logger){_configuration = configuration;_logger = logger;InitializeComponent();}private void BtnHello_Click(object sender, EventArgs e){Debug.WriteLine(_configuration.GetConnectionString("K3Connection"));//MessageBox.Show(".NET Core","Hello");_logger.LogInformation("Logger test");}}
