zoukankan      html  css  js  c++  java
  • NET Core 控制台程序读 appsettings.json 、注依赖、配日志、设 IOptions

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

    1、读 appsettings.json ,ConfigurationBuilder 上

    varconf = newConfigurationBuilder() .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 = newServiceCollection();//...services.AddSingleton<CosClient> ();IServiceProvider serviceProvider = services.BuildServiceProvider();varcosClient = 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

    完整代码:

    classProgram{

    staticasyncTask Main( string[] args) { varconf = newConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", true, true) .AddJsonFile("appsettings.Development.json", true, true) .Build(); IServiceCollection services = newServiceCollection(); services.AddLogging(builder => builder .AddConfiguration(conf.GetSection("Logging")) .AddConsole()); services.AddOptions(); services.Configure<CosClientOptions>(conf.GetSection( "cosClient")); services.AddSingleton<CosClient> (); IServiceProvider serviceProvider = services.BuildServiceProvider();

    varcosClient = serviceProvider.GetService<CosClient> (); }}

  • 相关阅读:
    jquery自调用匿名函数解析
    C# 分页
    C#一般处理程序获取Session
    Python全栈开发,Day12
    Python全栈开发,Day11
    Python全栈开发,Day10
    Python全栈开发,Day9
    Python全栈开发,Day8
    Python全栈开发,Day7
    Python全栈开发,Day6
  • 原文地址:https://www.cnblogs.com/lhxsoft/p/10595195.html
Copyright © 2011-2022 走看看