.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
IServiceProvider serviceProvider = services.BuildServiceProvider();var cosClient = serviceProvider.GetService
需要安装 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
services.AddOptions();
services.Configure
需要安装 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
services.AddSingleton
IServiceProvider serviceProvider = services.BuildServiceProvider();
var cosClient = serviceProvider.GetService();
}
}
}
}
作者:dotNET跨平台
来源:CSDN
原文:https://blog.csdn.net/sD7O95O/article/details/78694739
版权声明:本文为博主原创文章,转载请附上博文链接!