Biwen.Settings添加對IConfiguration&IOptions的集成支持

来源:https://www.cnblogs.com/vipwan/p/18204135
-Advertisement-
Play Games

Biwen.Settings 是一個簡易的配置項管理模塊,主要的作用就是可以校驗並持久化配置項,比如將自己的配置存儲到資料庫中,JSON文件中等 使用上也是很簡單,只需要在服務中註入配置, 比如我們有一個GithubSetting的配置項,我們只需要定義好對象然後註入到Service中即可: [De ...


Biwen.Settings 是一個簡易的配置項管理模塊,主要的作用就是可以校驗並持久化配置項,比如將自己的配置存儲到資料庫中,JSON文件中等
使用上也是很簡單,只需要在服務中註入配置,
比如我們有一個GithubSetting的配置項,我們只需要定義好對象然後註入到Service中即可:

    [Description("Github配置")]
    public class GithubSetting : ValidationSettingBase<GithubSetting>
    {
        [Description("Github用戶名")]
        public string? UserName { get; set; } = "vipwan";
        [Description("Github倉庫")]
        public string? Repository { get; set; } = "Biwen.Settings";
        [Description("Github Token")]
        public string? Token { get; set; } = "";
        public GithubSetting()
        {
            //驗證規則
            RuleFor(x => x.UserName).NotEmpty().Length(3, 128);
            RuleFor(x => x.Repository).NotNull().NotEmpty().Length(3, 128);
            RuleFor(x => x.Token).NotNull().NotEmpty().Length(3, 128);
        }
    }
@inject GithubSetting GithubSetting;//直接對象註入

儘管這樣已經足夠好用且便捷,但是對於習慣了使用IConfigurationIOptions的朋友來說還是有些不習慣,其實實現對IConfiguration的支持還是很簡單的,實現一下IConfigurationProvider即可,我們來動手實現一個名為BiwenSettingConfigurationProvider的Provider:

    internal class Events
    {
        /// <summary>
        /// Channel隊列
        /// </summary>
        public static readonly Channel<(bool IsChanged, string? SettingName)> ConfigrationChangedChannel = Channel.CreateUnbounded<(bool IsChanged, string? SettingName)>();
    }

    internal sealed class BiwenSettingConfigurationSource(bool autoRefresh = true) : IConfigurationSource
    {
        public IConfigurationProvider Build(IConfigurationBuilder builder) => new BiwenSettingConfigurationProvider(autoRefresh);
    }

    internal class BiwenSettingConfigurationProvider : ConfigurationProvider, IDisposable, IAsyncDisposable
    {
        public BiwenSettingConfigurationProvider(bool autoRefresh)
        {
            if (Settings.ServiceRegistration.ServiceProvider is null)
            {
                throw new BiwenException("必須首先註冊Biwen.Setting模塊,請調用:services.AddBiwenSettings()");
            }
            if (autoRefresh)
            {
                StartAlertAsync(cts.Token);
            }
        }

        private CancellationTokenSource cts = new();

        /// <summary>
        /// 使用Channel通知配置變更,如果有事件更新則重新載入
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task StartAlertAsync(CancellationToken cancellationToken)
        {
            _ = Task.Run(async () =>
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    _ = await Events.ConfigrationChangedChannel.Reader.ReadAsync(cancellationToken);
                    Load();
                    //通知配置變更
                    OnReload();
                }
            }, cancellationToken);

            return Task.CompletedTask;
        }
		//從SettingManager中載入配置項
        public override void Load()
        {
            Dictionary<string, string?> dics = [];

            using var scope = Settings.ServiceRegistration.ServiceProvider.CreateScope();
            var settingManager = scope.ServiceProvider.GetRequiredService<ISettingManager>();
            var settings = settingManager.GetAllSettings()!;
            foreach (var setting in settings)
            {
                if (setting.SettingContent is null) continue;
                if (JsonNode.Parse(setting.SettingContent) is not JsonObject json) continue;
                foreach (var item in json)
                {
                    dics.TryAdd($"{setting.SettingName}:{item.Key}", item.Value?.ToString());
                }
            }

            Data = dics;
        }

        public void Dispose()
        {
            cts.Cancel();
            Events.ConfigrationChangedChannel.Writer.Complete();
        }

        public ValueTask DisposeAsync()
        {
            cts.Cancel();
            Events.ConfigrationChangedChannel.Writer.Complete();
            return ValueTask.CompletedTask;
        }
    }

內部通過Channel實現變更通知,

    internal class ConfigurationMediratorDoneHandler(ILogger<ConfigurationMediratorDoneHandler> logger) : IMediratorDoneHandler
    {
        public Task OnPublishedAsync<T>(T @event) where T : ISetting, new()
        {            Events.ConfigrationChangedChannel.Writer.TryWrite((true, typeof(T).Name));
            logger.LogInformation($"Setting Changed: {typeof(T).Name},並通知Configuration刷新!");
            return Task.CompletedTask;
        }
    }

然後老規矩我們擴展一下IServiceCollection:


    public static class ServiceRegistration
    {
        internal static IServiceCollection AddBiwenSettingConfiguration(this IServiceCollection services)
        {
            //ConfigurationMediratorDoneHandler
            services.AddSingleton<IMediratorDoneHandler, ConfigurationMediratorDoneHandler>();
            return services;
        }

        /// <summary>
        /// 提供對IConfiguration,IOptions的支持
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="autoRefresh"></param>
        /// <returns></returns>
        public static ConfigurationManager AddBiwenSettingConfiguration(
            this ConfigurationManager manager, IServiceCollection serviceDescriptors, bool autoRefresh = true)
        {
            var sp = Settings.ServiceRegistration.ServiceProvider ?? throw new BiwenException("必須首先註冊Biwen.Setting模塊,請調用:services.AddBiwenSettings()");
            //添加訂閱
            if (autoRefresh)
            {
 serviceDescriptors.AddBiwenSettingConfiguration();
            }
            IConfigurationBuilder configBuilder = manager;
            configBuilder.Add(new BiwenSettingConfigurationSource(autoRefresh));
            var settings = ASS.InAllRequiredAssemblies.ThatInherit(typeof(ISetting)).Where(x => x.IsClass && !x.IsAbstract).ToList();
            //註冊ISetting
            settings.ForEach(x =>
            {
                //IOptions DI
                manager?.GetSection(x.Name).Bind(GetSetting(x, sp));
            });
            return manager;
        }

        static object GetSetting(Type x, IServiceProvider sp)
        {
            var settingManager = sp.GetRequiredService<ISettingManager>();
            var cache = sp.GetRequiredService<IMemoryCache>();

            //使用緩存避免重覆反射
            var md = cache.GetOrCreate($"GenericMethod_{x.FullName}", entry =>
            {
                MethodInfo methodLoad = settingManager.GetType().GetMethod(nameof(settingManager.Get))!;
                MethodInfo generic = methodLoad.MakeGenericMethod(x);
                return generic;
            });
            return md!.Invoke(settingManager, null)!;
        }
    }

最後在啟動時調用AddBiwenSettingConfiguration擴展即可

builder.Configuration.AddBiwenSettingConfiguration(builder.Services, true);

最後按下麵的形式註冊就可以了:

@inject GithubSetting GithubSetting;//直接對象註入
@inject IOptions<GithubSetting> IOP; //通過IOptions註入
@inject IConfiguration Configuration;//IConfiguration
...

源代碼我發佈到了GitHub,歡迎star! https://github.com/vipwan/Biwen.Settings
https://github.com/vipwan/Biwen.Settings/tree/master/Biwen.Settings/Extensions/Configuration


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 結構體 struct 是一種用戶自定義的值類型,常用於定義一些簡單(輕量)的數據結構。對於一些局部使用的數據結構,優先使用結構體,效率要高很多。 ...
  • 在很早之前,就想過開發一款抽獎軟體,卻一直沒有實際去做,最近經過一段時間的準備,終於開發出了一款基於WPF+Sqlite版的抽獎軟體,包括客戶端和管理端。本項目主要是為了熟悉WPF開發流程,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 安裝nuget包 Wesky.Net.OpenTools 1.0.8或以上版本。支持.net framework 4.6以上版本,以及所有.net core以及以上版本引用。 開發一個簡單的Winform界面,用來測試使用。如需該winform的demo,可以在公眾號【Dotnet Dancer】後 ...
  • 最近群里有個小伙伴把Dapper遷移SqlSugar幾個不能解決的問題進行一個彙總,我正好寫一篇文章來講解一下 一、sql where in傳參問題: SELECT * FROM users where id IN @ids 答: SqlSugar中應該是 var sql="SELECT * FRO ...
  • 自定義分頁控制項 tip: 該控制項的樣式用的是materialDesign庫,需要下載Nuget包 Code Xaml <UserControl x:Class="TestTool.CustomControls.PagingControl" xmlns="http://schemas.microsof ...
  • 自定義可移動點二維坐標軸控制項 目錄 路由參數 坐標軸控制項定義 Demo 路由參數 X_YResultCollection為當前X軸對應Y軸值存儲字典 public class ResultCollectionChangedEventArgs(RoutedEvent routedEvent, obje ...
  • 前言 VB.NET,全名Visual Basic .NET,是Microsoft .NET框架的一部分,是一種面向對象的編程語言。它繼承了Visual Basic的易用性,同時增加了對面向對象編程的支持。VB.NET提供了大量的內置函數,使得開發者可以更容易地處理字元串、數學計算、文件和目錄訪問等任 ...
  • EDP是一套集組織架構,許可權框架【功能許可權,操作許可權,數據訪問許可權,WebApi許可權】,自動化日誌,動態Interface,WebApi管理等基礎功能於一體的,基於.net的企業應用開發框架。通過友好的編碼方式實現數據行、列許可權的管控。 ...
一周排行
    -Advertisement-
    Play Games
  • 一:背景 1. 講故事 前些天有位朋友找到我,說他們的程式會偶發性的卡死一段時間,然後又好了,讓我幫忙看下怎麼回事?窗體類的程式解決起來相對來說比較簡單,讓朋友用procdump自動抓一個卡死時的dump,拿到dump之後,上 windbg 說話。 二:WinDbg 分析 1. 主線程在做什麼 要想 ...
  • 功能說明 使用ListView時,希望可以在單元格顯示圖片或其他控制項,發現原生的ListView不支持,於是通過拓展,實現ListView可以顯示任意控制項的功能,效果如下: 實現方法 本來想著在單元格裡面實現控制項的自繪的,但是沒找到辦法,最後是通過在單元格的錶面顯示對應控制項的,浮於錶面達到目的。 實 ...
  • 由於.NET Framework 4.0 是比較古老的版本,只有New Relic 7.0以下的版本才會支持.NET Framework 4.0的引用程式。 Technical support for .NET Framework 4.0 or lower 你可以參考這個官方Install New ...
  • 前言 隨著 DEV24.1.3 的發佈,XAF Blazor 中的屬性編輯器(PropertyEditor)也進行了很大的改動,在使用體驗上也更接近 WinForm 了,由於進行了大量的封裝,理解上沒有 WinForm 直觀,所以本文通過對屬性編輯器的原理進行解析,並對比新舊版本中的變化,使大家能夠 ...
  • OPC基金會提供了OPC UA .NET標準庫以及示常式序,但官方文檔過於簡單,光看官方文檔和示常式序很難弄懂OPC UA .NET標準庫怎麼用,花了不少時間摸索才略微弄懂如何使用,以下記錄如何從一個控制台程式開發一個OPC UA伺服器。 安裝Nuget包 安裝OPCFoundation.NetSt ...
  • 今天在技術群里,石頭哥向大家提了個問題:"如何在一個以System身份運行的.NET程式(Windows Services)中,以其它活動的用戶身份啟動可互動式進程(桌面應用程式、控制台程式、等帶有UI和互動式體驗的程式)"? 我以前有過類似的需求,是在GitLab流水線中運行帶有UI的自動化測試程 ...
  • .Net 中提供了一系列的管理對象集合的類型,數組、可變列表、字典等。從類型安全上集合分為兩類,泛型集合 和 非泛型集合,傳統的非泛型集合存儲為Object,需要類型轉。而泛型集合提供了更好的性能、編譯時類型安全,推薦使用。 ...
  • 在以前我做程式的時候,一般在登錄視窗裡面顯示程式名稱,登錄視窗一般設置一張背景圖片,由於程式的名稱一般都是確定的,所以也不存在太大的問題,不過如果客戶定製不同的系統的時候,需要使用Photoshop修改下圖層的文字,再生成圖片,然後替換一下也可以了。不過本著減少客戶使用繁瑣性,也可以使用空白名稱的通... ...
  • 一:背景 1. 講故事 在dump分析的過程中經常會看到很多線程卡在Monitor.Wait方法上,曾經也有不少人問我為什麼用 !syncblk 看不到 Monitor.Wait 上的鎖信息,剛好昨天有時間我就來研究一下。 二:Monitor.Wait 底層怎麼玩的 1. 案例演示 為了方便講述,先 ...
  • 目錄前言學習參考過程總結: 前言 做個自由仔。 學習參考 ChatGpt; https://www.cnblogs.com/zhili/p/DesignPatternSummery.html(大佬的,看了好多次) 過程 原由: 一開始只是想查查鏈式調用原理,以為是要繼承什麼介面,實現什麼方法才可以實 ...