ASP.NET Core實現類庫項目讀取配置文件


前言

之前繼續在學習多線程方面的知識,忽然這兩天看到博問中有個園友問到如何在.net core類庫中讀取配置文件,當時一下蒙了,這個提的多好,我居然不知道,於是這兩天了解了相關內容才有此篇博客的出現,正常來講我們在應用程序目錄下有個appsettings.json文件對於相關配置都會放在這個json文件中,但是要是我建立一個類庫項目,對於一些配置比如密鑰或者其他需要硬編碼的數據放在JSON文件中,在.net core之前配置文件為web.config並且有相關的類來讀取節點上的數據,現如今在.net core中為json文件,那么我們該如何做?本文就此應運而生。

.NET Core類庫項目讀取JSON配置文件

在應用程序目錄下添加JSON文件是進行如下配置:

                var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
               Configuration = builder.Build();

然后讀取配置文件的節點,如下:

        public void ConfigureServices(IServiceCollection services)
        {

            services.Configure<BlogViewModel>(Configuration.GetSection("JeffckySettings"));
            ......
         }

但是如果項目是在類庫中呢,當然我們也可以將配置值放在應用程序下的appsettings.json中,但是為了不讓其json文件中看起來顯得非常臃腫同時在類庫中的配置數據我們理應放在類庫中來統一管理,所以我們得另外再想方案,總不能在類庫中建立startup.cs類,再來實例化Configuration吧,這樣想想應該也是可以,我沒嘗試過,難道就沒有很簡單的方式么,難道就不能像.net core之前用類來讀取web.config我們只需要給出鍵而得到值嗎?或者說通過強類型配置來統一管理配置數據,這個才應該是我們嘗試的方向。好了,說了這么多,我們就開干。我們首先來復習下.net core中是如何獲取應用程序路徑的。

.NET Core獲取應用程序路徑

在.NET 4.X之前獲取當前應用程序根目錄路徑和名稱可以通過如下獲取

var basePath = AppDomain.CurrentDomain.BaseDirectory;
var appName = AppDomain.CurrentDomain.ApplicationIdentity.FullName;

當然也可以通過如下來獲取應用程序根目錄而不是得到bin目錄

Directory.GetCurrentDirectory()

在.net core中獲取bin目錄路徑通過如下來獲取更加簡潔。

AppContext.BaseDirectory

在.NET 4.X之前獲取應用程序集名稱通過如下來獲取:

Assembly.GetEntryAssembly().GetName().Name;

在.net core中通過如下來獲取:

var name = typeof(T).GetTypeInfo().Assembly.GetName().Name;

版本通過如下來獲取(.net core也一樣):

Assembly.GetEntryAssembly().GetName().Version.ToString()

在類庫項目中我們利用強類型配置來實現讀取配文件數據,我們首先需要下載如下擴展。

在ConfigurationBuilder類中如下一個Add添加方法:

         //
        // 摘要:
        //     Adds a new configuration source.
        //
        // 參數:
        //   source:
        //     The configuration source to add.
        //
        // 返回結果:
        //     The same Microsoft.Extensions.Configuration.IConfigurationBuilder.
        public IConfigurationBuilder Add(IConfigurationSource source);

對於 AddJsonFile 擴展方法來添加JSON文件名,文件路徑已經通過 SetBasePath() 方法來實現,一切配置都是基於 IConfigurationBuilder 接口,其中就有一個 JsonConfigurationSource 類,實現如下:

 //
    // 摘要:
    //     Represents a JSON file as an Microsoft.Extensions.Configuration.IConfigurationSource.
    public class JsonConfigurationSource : FileConfigurationSource
    {
        public JsonConfigurationSource();

        //
        // 摘要:
        //     Builds the Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider
        //     for this source.
        //
        // 參數:
        //   builder:
        //     The Microsoft.Extensions.Configuration.IConfigurationBuilder.
        //
        // 返回結果:
        //     A Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider
        public override IConfigurationProvider Build(IConfigurationBuilder builder);
    }

我們再看其父類就有一個添加JSON文件路徑的方法,如下:

所以我們從這里可以看出添加JSON文件的方法除了通過擴展方法來實現外還有直接實例化JsonConfigurationSource來實現,如下:

IConfiguration config = new ConfigurationBuilder()
                .SetBasePath(currentClassDir)
                .AddJsonFile("appsettings.json", false, true)
                .Add(new JsonConfigurationSource { Path = "appsettings.json", Optional = false, ReloadOnChange = true })
                .Build();

上述添加JSON文件皆可,我發現添加JSON文件必須設置JSON文件所在的目錄即必須首先要設置 SetBasePath 方法,否則會報如下錯誤:

我們搞個測試JSON文件放在當前項目(StudyEFCore.Data)中如下:

 

最終讀取類庫項目JSON配置文件,將其封裝起來就成了如下這個樣子:

    public class JsonConfigurationHelper
    {
        public T GetAppSettings<T>(string key) where T : class, new()
        {
            var baseDir = AppContext.BaseDirectory;
            var indexSrc = baseDir.IndexOf("src");
            var subToSrc = baseDir.Substring(0, indexSrc);
            var currentClassDir = subToSrc + "src" + Path.DirectorySeparatorChar + "StutdyEFCore.Data";

            IConfiguration config = new ConfigurationBuilder()
                .SetBasePath(currentClassDir)
                .Add(new JsonConfigurationSource { Path = "appsettings.json", Optional = false, ReloadOnChange = true })
                .Build();
            var appconfig = new ServiceCollection()
                .AddOptions()
                .Configure<T>(config.GetSection(key))
                .BuildServiceProvider()
                .GetService<IOptions<T>>()
                .Value;
            return appconfig;
        }
    }

 

由上有一個還未解決的問題就是如何得到當前類庫項目的路徑,沒有想到一個好的法子,不知看到此文的你有何高見。簡短的調用則是如下:

            var config = new JsonConfigurationHelper();
            var person = config.GetAppSettings<Person>("JeffckySettings");
            var name = person.Name;
            var age = person.Age;

結果如下:

 

我們將其類修改為 ConfigurationManager ,然后將其 GetAppSettings 方法定義為靜態方法,最后如下調用是不是滿足了在.net core之前讀取web.config中配置數據的問題。哈哈哈:

 var person = ConfigurationManager.GetAppSettings<Person>("JeffckySettings");

總結

本節我們詳細講解了在.net core類庫項目中如何讀取JSON配置中的數據但是還是有點不足,你有何高見?


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM