当前位置: 移动技术网 > IT编程>开发语言>.net > .Net Core 实践 - 如何在控制台应用(.Net Core)使用appsettings.json配置

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

2019年02月19日  | 移动技术网IT编程  | 我要评论

家乐福购物卡查询,血溅归乡路,澳门金沙301055

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

参考文章与说明

说明:

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网