首页 > 移动平台 > 详细

.net 5.0 - 控制台加载appsettings.json文件

时间:2021-05-13 00:47:37      阅读:30      评论:0      收藏:0      [点我收藏+]
 引用NuGet

 Microsoft.Extensions.Configuration

 Microsoft.Extensions.Configuration.FileExtensions

 Microsoft.Extensions.Configuration.Json

 在控制台应用项目下,创建appsettings.json
{
  "ConnectionStrings": {
    "dbName": "server=localhost;database=hr;PORT=3306;uid=root;pwd=123456;charset=gb2312"
  },
  "AppSettings": {
    "Url": "12"
  }
}

 特别注意:

技术分享图片

创建调用类及调用方式

 

using Microsoft.Extensions.Configuration;
using System;
using System.IO;

namespace CustomAttributes.Model
{
    public class Appsettings
    {
        private IConfigurationRoot Configuration;

        private Appsettings()
        {
            var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
            Configuration = builder.Build();
        }

        private static readonly Lazy<Appsettings> InstanceLock = new Lazy<Appsettings>(() => new Appsettings()
        {

        });

        public static Appsettings Instance
        {
            get
            {
                return InstanceLock.Value;
            }
        }

        public string GetByKey(string key)
        {
            return Configuration.GetSection(key).Value;
        }

        public string GetConnectionString()
        {
            return Configuration.GetConnectionString("dbName");
        }
    }
}

  

using CustomAttributes.Model;
using System;

namespace CustomAttributesApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Appsettings.Instance.GetByKey("AppSettings:Url"));
            Console.WriteLine(Appsettings.Instance.GetConnectionString());
        }
    }
}

  

技术分享图片

 

.net 5.0 - 控制台加载appsettings.json文件

原文:https://www.cnblogs.com/gygtech/p/14762431.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!