ASP.NET Core實現類庫項目讀取配置文件
.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");
ASP.NET Core實現類庫項目讀取配置文件