.Net 配置系统-数据库配置提供者

集群部署的项目中,如果每个服务器都使用本地的配置文件,每次修改都要挨个修改,费时费力还容易出错。

将配置信息放到数据库的表中,然后通过程序读取配置项,可以单独做一个配置服务器,其他服务器均从配置服务器中读取配置,避免了上述问题。

下面用示例展示用法:(数据库使用SqlServer,其他也可以)

1.数据库中建表T_Configs,三个字段Id、Name、Value,Id设置为主键并自增长。

往表中插入配置数据,支持json格式:

 程序需要引用的包:

Program.cs

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Data.SqlClient;

namespace DBConfigProvider
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceCollection services = new ServiceCollection();
            services.AddScoped<TestWebConfig>();//往DI容器中注册自定义类
            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            string connStr = "server=.;DataBase=yzk;uid=sa;pwd=123456";//数据库连接

            //读取数据库表中的配置项并加载到ConfigurationBuilder
            configurationBuilder.AddDbConfiguration(() => new SqlConnection(connStr), reloadOnChange: true, reloadInterval: TimeSpan.FromSeconds(2));

            IConfigurationRoot root = configurationBuilder.Build();

            //将Options添加到DI容器中
            services.AddOptions()
                .Configure<CusConfig>(e => root.Bind(e))//将CusConfig对象绑定到根节点上面
                .Configure<Proxy>(e => root.GetSection("proxy").Bind(e));

            //打印输出配置信息
            using (var sp = services.BuildServiceProvider())
            {
                var c = sp.GetRequiredService<TestWebConfig>();
                c.Test();
                Console.ReadKey(); 
            }
        }


    }
}

CusConfig.cs

namespace DBConfigProvider
{
    class CusConfig
    {
        public string name { get; set; }
        public string age { get; set; }
        public Proxy proxy { get; set; }
    }

    class Proxy
    {
        public string address { get; set; }
        public int port { get; set; }
    }
}

TestWebConfig.cs

using Microsoft.Extensions.Options;
using System;

namespace DBConfigProvider
{
    class TestWebConfig
    {
        private IOptionsSnapshot<CusConfig> optWC;

        public TestWebConfig(IOptionsSnapshot<CusConfig> optWC)
        {
            this.optWC = optWC;
        }

        public void Test()
        {
            var wc = optWC.Value;
            Console.WriteLine(wc.name);
            Console.WriteLine(wc.age);
            Console.WriteLine(wc.proxy.address);
            Console.WriteLine(wc.proxy.port);
        }
    }
}

执行结果:

 

代码中调用的AddDbConfiguration方法,是杨中科老师自己开发的专门用于读取数据库配置的程序集。具体使用方法可以参考文档:

https://github.com/yangzhongke/Zack.AnyDBConfigProvider/blob/main/README_CHS.md

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值