本文主要内容参考自下面几篇博客,操作步骤只是为了做个备注方便回忆,具体细节和原理还是推荐大家自行阅读下面几篇博客:

  1. 新建 .NET Core 3.1 WinForm 项目
  2. NuGet 安装 Microsoft.Extensions.Hosting
  3. 配置 EF Core(这步可以参考官方的 ASP.NET Core 教程)

    1. NuGet 安装 EF Core 相关包
    2. 创建实体类
    3. 创建 DbContext

      1. public class K3DbContext : DbContext
      2. {
      3. public K3DbContext(DbContextOptions<K3DbContext> options) : base(options)
      4. {
      5. }
      6. public DbSet<XX> XXs { get; set; }
      7. }
  4. 手动添加 appsettings.json 文件,并将其设置为总是复制到输出目录

    1. {
    2. "Logging": {
    3. "LogLevel": {
    4. "Default": "Information"
    5. }
    6. },
    7. "AllowedHosts": "*",
    8. "ConnectionStrings": {
    9. "K3Connection": "server=10.XX.XX.XXX;Database=K3;User ID=XX;Password=XX"
    10. }
    11. }
  5. 修改 Main() 代码

    1. [STAThread]
    2. static void Main()
    3. {
    4. Application.SetHighDpiMode(HighDpiMode.SystemAware);
    5. Application.EnableVisualStyles();
    6. Application.SetCompatibleTextRenderingDefault(false);
    7. // CreateDefaultBuilder 里面自动注入并配置了 IConfiguration
    8. var hostBuilder = Host.CreateDefaultBuilder()
    9. .ConfigureServices((hostContext, services) =>
    10. {
    11. services.AddLogging(configure => configure.AddDebug());
    12. services.AddTransient<Form1>();
    13. services.AddDbContext<K3DbContext>(options =>
    14. options.UseSqlServer(hostContext.Configuration.GetConnectionString("K3Connection")));
    15. });
    16. var builderDefault = hostBuilder.Build();
    17. using (var serviceScope = builderDefault.Services.CreateScope())
    18. {
    19. var services = serviceScope.ServiceProvider;
    20. var form1 = services.GetRequiredService<Form1>();
    21. Application.Run(form1);
    22. }
    23. }
  6. 在 Form1 中使用注入的实例

    1. public partial class Form1 : Form
    2. {
    3. private readonly IConfiguration _configuration;
    4. private readonly ILogger<Form1> _logger;
    5. public Form1(IConfiguration configuration, ILogger<Form1> logger)
    6. {
    7. _configuration = configuration;
    8. _logger = logger;
    9. InitializeComponent();
    10. }
    11. private void BtnHello_Click(object sender, EventArgs e)
    12. {
    13. Debug.WriteLine(_configuration.GetConnectionString("K3Connection"));
    14. //MessageBox.Show(".NET Core","Hello");
    15. _logger.LogInformation("Logger test");
    16. }
    17. }