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> (); }}

  • 相关阅读:
    关于yarn的spark配置属性
    spark1.2.0编译
    sqoop1.99.4 JAVA API操作
    数据库范式(1NF 2NF 3NF BCNF)
    HTTP协议详解【转载】
    ESI 动态缓存技术[转载]
    ESI+varnish页面片段缓存
    用 Gearman 分发 PHP 应用程序的工作负载【转载】
    介绍 JSON的
    跨多种环境部署 Gearman -改善应用程序性能和降低服务器负载
  • 原文地址:https://www.cnblogs.com/lhxsoft/p/10595195.html
Copyright © 2011-2022 走看看