.Net Core 实践 - 如何在控制台应用(.Net Core)使用appsettings.json配置

新建控制台应用(.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地址

https://github.com/PuzzledAlien/DotNetCore_Practice/tree/master/%E5%A6%82%E4%BD%95%E5%9C%A8%E6%8E%A7%E5%88%B6%E5%8F%B0%E5%BA%94%E7%94%A8(.Net%20Core)%E4%BD%BF%E7%94%A8appsetting.json%E9%85%8D%E7%BD%AE

参考文章与说明

说明:

posted @ 2019-02-18 17:28 repeatedly 阅读(...) 评论(...) 编辑 收藏