.net core Winform 添加DI和读取配置、添加log
阅读原文时间:2023年07月08日阅读:3

首先新建配置类

public class CaptureOption
{

    /// <summary>  
    /// 是否自启  
    /// </summary>  
    public bool AutoStart { get; set; }

    /// <summary>  
    /// 是否设置为壁纸  
    /// </summary>  
    public bool SetWallpaper { get; set; } = true;  

}

然后添加appsettings.json, 复制到输出目录选择 如果较新则复制

"CaptureOptions": {
"AutoStart": false,
"SetWallpaper": true
}

nuget 安装

Microsoft.Extensions.Configuration.Json

Microsoft.Extensions.DependencyInjection

Microsoft.Extensions.Options.ConfigurationExtensions

Microsoft.Extensions.Logging

Microsoft.Extensions.Logging.Debug

如果需要httpclientFactory则还需要安装 Microsoft.Extensions.Http

最后是main函数里配置

    static void Main()  
    {  
        Application.SetHighDpiMode(HighDpiMode.SystemAware);  
        Application.EnableVisualStyles();  
        Application.SetCompatibleTextRenderingDefault(false);

        //添加配置读取  
        var config = new ConfigurationBuilder().AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)  
            .Build();

        //添加DI  
        var services = new ServiceCollection();  
        services.AddOptions();  
        services.AddSingleton(config);  
        services.Configure<CaptureOption>(config.GetSection("CaptureOptions"));  
        services.AddLogging(builder =>  
        {  
            builder.AddDebug(); //添加日志输出

        });   

        //添加主窗体为单例   
        services.AddSingleton(typeof(MainForm));   

        var serviceProvider = services.BuildServiceProvider();   
        Application.Run(services.BuildServiceProvider().GetRequiredService<MainForm>()); }

最后通过注入IOptionsSnapshot 能监听到appsettings.json的变化