新建控制台应用(.Net Core)程序
添加json文件,命名为appsettings.json,设置文件属性 如果较新则复制
。添加内容如下
{
"MyWords" : "Hello World!"
}
nuget添加相关引用
依次添加以下引用
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.FileExtensions
Microsoft.Extensions.Configuration.Json
Microsoft.Extensions.Hosting
实现思路
在看到《.NET 通用主机》的文章之后,认为可以尝试借助GenericHost更优雅的在Console项目中使用appsetings.json进行项目配置。
Main入口代码如下:
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace ConsoleApp1
{
class Program
{
private static IConfiguration _appConfiguration;
static void Main(string[] args)
{
var hostBuilder = new HostBuilder().ConfigureAppConfiguration((hostContext, configApp) =>
{
var hostingEnvironment = hostContext.HostingEnvironment;
_appConfiguration = AppConfigurations.Get(hostingEnvironment.ContentRootPath, hostingEnvironment.EnvironmentName);
}).ConfigureServices((hostContext, services) =>
{
//注入IConfiguration到DI容器
services.AddSingleton(_appConfiguration);
//注入MyService到DI容器
services.AddSingleton<IMyService, MyService>();
});
//初始化通用主机
var host = hostBuilder.Build();
//获取MyService
var myService = host.Services.GetService<IMyService>();
//调用SayMyWords方法
myService.SayMyWords();
Console.ReadKey();
}
}
}
demo地址
参考文章与说明
说明:
- 通用主机Hosting的开源地址:https://github.com/aspnet/Extensions/tree/master/src/Hosting