如何自定义配置

  1. IConfigurationSource   build()方法
  2. IConfigurationProvider
 1 using CSRedis;
 2 using Microsoft.Extensions.Configuration;
 3 using Microsoft.Extensions.Primitives;
 4 using System;
 5 using System.Collections.Generic;
 6 using System.Text;
 7 
 8 namespace WorkerService
 9 {
10     public class RedisConfigurationSource : IConfigurationSource
11     {
12         private readonly RedisConfigurationOptions _options;
13 
14         public RedisConfigurationSource(RedisConfigurationOptions options)
15         {
16             _options = options;
17         }
18 
19         public IConfigurationProvider Build(IConfigurationBuilder builder)
20         {
21             return new RedisConfigurationProvider(_options);
22         }
23     }
24     public class RedisConfigurationOptions
25     {
26         public bool AutoReload { get; set; }
27         public string ConnectionString { get; set; }
28         public string HashCacheKey { get; set; }
29         public string HashCacheChannel { get; set; }
30     }
31 
32 
33     public class RedisConfigurationProvider : ConfigurationProvider
34     {
35         private CSRedisClient _redisClient;
36         private readonly RedisConfigurationOptions _options;
37 
38         public RedisConfigurationProvider(RedisConfigurationOptions options)
39         {
40             _options = options;
41             _redisClient = new CSRedisClient(_options.ConnectionString);
42             if (options.AutoReload)
43             {
44                 //利用Redis的发布-订阅重新加载配置
45                 _redisClient.Subscribe((_options.HashCacheChannel, msg => Load()));
46             }
47         }
48 
49         public override void Load()
50         {
51             Data = _redisClient.HGetAll<string>(_options.HashCacheKey) ?? new Dictionary<string, string>();
52         }
53     }
54 }

 

using AgileConfig.Client;
using HXH.DAL;
using HXH.DAL.DataAccess.DbProvider;
using HXH.Tools;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace WorkerService
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            //.ConfigureAppConfiguration((context, config) =>
            //{
            //    //读取本地配置
            //    var localconfig = new ConfigurationBuilder()
            //                     .SetBasePath(Directory.GetCurrentDirectory())
            //                     .AddJsonFile("appsettings.json").Build();
            //    //从本地配置里读取AgileConfig的相关信息
            //    var appId = localconfig["AgileConfig:appId"];
            //    var secret = localconfig["AgileConfig:secret"];
            //    var nodes = localconfig["AgileConfig:nodes"];
            //    //new一个client实例
            //    var configClient = new ConfigClient(appId, secret, nodes,"");
            //    //使用AddAgileConfig配置一个新的IConfigurationSource
            //    config.AddAgileConfig(configClient);
            //    //找一个变量挂载client实例,以便其他地方可以直接使用实例访问配置
            //    //注册配置项修改事件
            //    configClient.ReLoaded += ConfigClient_ConfigChanged; ;
            //})
            .ConfigureAppConfiguration(config =>
            {
                //读取本地配置
                var localconfig = new ConfigurationBuilder()
                                 .SetBasePath(Directory.GetCurrentDirectory())
                                 .AddJsonFile("appsettings.json").Build();
                config.AddRedisConfiguration(new RedisConfigurationOptions 
                {
                    AutoReload=Convert.ToBoolean(localconfig.GetSection("ConfigCenter:AutoReload").Value),
                    ConnectionString = localconfig.GetSection("ConfigCenter:ConnectionString").Value,
                    HashCacheKey = localconfig.GetSection("ConfigCenter:HashCacheKey").Value,
                    HashCacheChannel = localconfig.GetSection("ConfigCenter:HashCacheChannel").Value,
                });
            })
                .ConfigureServices((hostContext, services) =>
                {
                    //AppInfoOptions sample = new AppInfoOptions();
                    //sample.AppName = hostContext.Configuration["App:AppName"];
                    //sample.AppVersion = hostContext.Configuration["App:AppVersion"];
                    //services.AddSingleton<IOptions<AppInfoOptions>>(sample);
                    //services.Configure<AppInfoOptions>(hostContext.Configuration.GetSection(""));
                    ConfigHelper.Configuration = hostContext.Configuration;
                    //对MYSQL数据库连接进行初始化,注意所传的参数
                    //new AppsettingsUtility().Initial(hostContext.Configuration["HXH_DataBase:Sandbox:connectionString"], hostContext.Configuration["HXH_DataBase:Sandbox:providerName"]);

                    //DbHelper.DbType = (DatabaseType)Enum.Parse(typeof(DatabaseType), "MySql", true);

                    ////Redis服务依赖
                    ////RedisHelper.redisClient.InitConnect(hostContext.Configuration);

                    ////DI依赖注入
                    //services.AddTransientAssembly("HXH.Tools");
                    //services.AddScopedAssembly("HXH.Repository");
                    //services.AddScopedAssembly("HXH.Service");
                    //services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

                    services.AddHostedService<TimedHostedService>();
                });

        private static void ConfigClient_ConfigChanged(ConfigReloadedArgs obj)
        {
            Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(obj));
        }
    }


    public class AppInfoOptions 
    {
        public string AppName { get; set; }
        public string AppVersion { get; set; }
    }

}

 

posted @ 2024-02-23 09:41  每天学习一点哈哈哈  阅读(17)  评论(0编辑  收藏  举报