欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net core 2.0类库项目读取配置文件

程序员文章站 2024-01-16 10:59:52
1.首先在类库项目中添加 这3个库。 2.在类库项目中添加AppSetting.cs。代码如下: using Microsoft.Extensions.Configuration;using System;using System.Collections.Generic;using System.I ......

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

asp.net core 2.0类库项目读取配置文件

这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;
        }