.NET Core 控制台程序读 appsettings.json 、注依赖、配日志、设 IOptions

.NET Core 控制台程序没有 ASP.NET Core 的 IWebHostBuilder 与 Startup.cs ,那要读 appsettings.json、注依赖、配日志、设 IOptions 该怎么办呢?因为这些操作与 ASP.NET Core 无依赖,所以可以自己动手,轻松搞定。

1、读 appsettings.json ,ConfigurationBuilder 上

var conf = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", true, true)
    .AddJsonFile("appsettings.Development.json", true, true)
    .Build();

需要安装 nuget 包 Microsoft.Extensions.Configuration 、Microsoft.Extensions.Configuration.FileExtensions 、Microsoft.Extensions.Configuration.Json

2、注依赖,IServiceCollection + IServiceProvider 一起来

IServiceCollection services = new ServiceCollection();
//...
services.AddSingleton<CosClient>();
IServiceProvider serviceProvider = services.BuildServiceProvider();
var cosClient = serviceProvider.GetService<CosClient>();

需要安装 nuget 包 Microsoft.Extensions.DependencyInjection 

3、配日志, AddLogging 与 ILoggingBuilder 肩并肩

services.AddLogging(builder => builder    
    .AddConfiguration(conf.GetSection("Logging"))
    .AddConsole());

需要安装 nuget 包 Microsoft.Extensions.Logging 、Microsoft.Extensions.Logging.Configuration 、Microsoft.Extensions.Logging.Console

4、设IOptions,AddOptions() 与 Configure<T> 齐步走

services.AddOptions();
services.Configure<CosClientOptions>(conf.GetSection("cosClient"));

需要安装 nuget 包 Microsoft.Extensions.Options 与 Microsoft.Extensions.Options.ConfigurationExtensions

完整代码:

class Program
{
    static async Task Main(string[] args)
    {
        var conf = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", true, true)
            .AddJsonFile("appsettings.Development.json", true, true)
            .Build();

        IServiceCollection services = new ServiceCollection();
        services.AddLogging(builder => builder
            .AddConfiguration(conf.GetSection("Logging"))
            .AddConsole());
        services.AddOptions();
        services.Configure<CosClientOptions>(conf.GetSection("cosClient"));
        services.AddSingleton<CosClient>();

        IServiceProvider serviceProvider = services.BuildServiceProvider();
        var cosClient = serviceProvider.GetService<CosClient>();
    }
}
posted @ 2017-11-08 11:13  dudu  阅读(1876)  评论(1编辑  收藏  举报