1.首先在类库项目中添加

这3个库。

2.在类库项目中添加AppSetting.cs。代码如下:

using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace EntityDemo
{
    public class AppSetting
    {
        private static readonly object objLock = new object();      //锁
        private static AppSetting instance = null;

        private IConfigurationRoot Config { get; }
        //读取json文件
        private AppSetting()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            Config = builder.Build();
        }
        //加锁
        public static AppSetting GetInstance()
        {
            if (instance == null)
            {
                lock (objLock)
                {
                    if (instance == null)
                    {
                        instance = new AppSetting();
                    }
                }
            }

            return instance;
        }
        //读取方法
        public static string GetConfig(string name)
        {
            return GetInstance().Config.GetSection(name).Value;
        }
    }
}

3.简单调用

3.1配置文件配置

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "TestDb": "server=localhost;port=3306;database=master;user=;password=;charset=utf8;"
  }
}

3.2类中调用

   public string TestConfig()
        {
            string str = AppSetting.GetConfig("ConnectionStrings:TestDb");
            return str;
        }

 

posted on 2018-07-23 15:01  雾夜飞虫  阅读(387)  评论(2编辑  收藏  举报