如何在ASP.NET Core 的任意類中注入Configuration
遇到的問題
我已經(jīng)通讀了 MSDN 上關(guān)于 Configuration 的相關(guān)內(nèi)容,文檔說可實現(xiàn)在 application 的任意位置訪問 Configuration .
下面是 Startup.cs 的模板代碼。
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsEnvironment("Development"))
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
app.UseMvc();
}
}
我知道可以通過 DI 的方式將 Configuration 注入到 Controller,Service,Repository 等地方,但在真實項目中,會有很多類是在這三塊之外的。
請問我如何在這三大塊之外實現(xiàn) Configuration 的注入呢?換句話說:可以在任意類中實現(xiàn) Configuration 的注入... 😭
解決方案
在 .NET Core 中你可以將 IConfiguration 作為參數(shù)直接注入到 Class 的構(gòu)造函數(shù)中,這本身就是可以的,如下代碼所示:
public class MyClass
{
private IConfiguration configuration;
public MyClass(IConfiguration configuration)
{
ConnectionString = new configuration.GetValue<string>("ConnectionString");
}
}
接下來要做的就是 new MyClass(),很顯然這樣做是不行的,因為你的構(gòu)造函數(shù)還需要一個 IConfiguration 類型的參數(shù),所以你需要將 new MyClass() 塞入到 Asp.NET Core 的 DI 鏈中。
思路也很簡單。
- 將 MyClass 注入到 ServiceCollection 容器中
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<MyClass>();
services.AddControllers();
}
- 生成 MyClass 實例
在 MyClass 的調(diào)用方處通過 DI 生成實例,這里以 Controller 處為例,如下代碼所示:
public class MyController : ControllerBase
{
private MyClass _myClass;
public MyController(MyClass myClass)
{
_myClass = myClass;
}
}
這樣是不是就完美的實現(xiàn)了在 MyClass 中使用 Configuration 了?
還有一種更簡單粗暴的做法,無需注入, 只需定義一個靜態(tài)的類,在 Startup 中將 IConfiguration 賦值給該靜態(tài)類保存即可,參考代碼如下:
public static class MyAppData
{
public static IConfiguration Configuration;
}
public Startup(IConfiguration configuration)
{
Configuration = configuration;
MyAppData.Configuration = configuration;
}
然后就可以在項目的各處訪問 MyAppData.Configuration 啦。
總結(jié)
在 Asp.Net 時代,讀取配置文件真的是一點都不需要操心,一個 ConfigurationManager 走天下😄😄😄,比如下面的代碼:
private static string AppKey = ConfigurationManager.AppSettings["AppKey"];
反倒在 Asp.Net Core 中卻有點懵逼了,就像題主說的,我想在任意類中都可以讀取 Configuration 😂😂😂,問題的差異來自于 Asp.Net Core 使用了 DI先行 的打法,哈哈,忘了過去吧,從 ♥ 開始 ...
以上就是如何在 ASP.NET Core 的任意類中注入Configuration 的詳細(xì)內(nèi)容,更多關(guān)于ASP.NET Core 注入Configuration 的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
asp.net中如何批量導(dǎo)出access某表內(nèi)容到word文檔
最近有項目需求是這樣的,需要將某表中的每一條記錄中的某些內(nèi)容導(dǎo)出在一個word文檔中。下面小編就把我的解決辦法分享給大家,供大家參考2015-10-10
HTML服務(wù)器控件和WEB服務(wù)器控件的區(qū)別和聯(lián)系介紹
學(xué)習(xí)asp.net的時候一會用Html服務(wù)器控件,一會用Web服務(wù)器控件,起初做起例子來也挺迷糊的,下面對這兩個控件研究了一下做個筆記在此與大家分享下,感興趣的朋友可以了解下2013-08-08
ASPX向ASCX傳值以及文本創(chuàng)建圖片(附源碼)
把用戶在TextBox輸入的文字創(chuàng)建為一個圖片,ASCX的ImageButton的ImageUrl重新指向這剛產(chǎn)生的圖片,接下來介紹下ASPX向ASCX傳值,感興趣的朋友可以參考下哈2013-03-03
asp.net 自動將漢字轉(zhuǎn)換成拼音第一個字母
把漢字轉(zhuǎn)換成拼音第一個字母 的實現(xiàn)代碼2009-03-03
google suggest 下拉菜單實現(xiàn)代碼(asp.net版本)
原來發(fā)表過,是asp版本的,但是不支持上下鍵,現(xiàn)在后臺處理程序用.net寫的。代碼進(jìn)行部分優(yōu)化。2009-07-07
使用VS2022在ASP.NET?Core中構(gòu)建輕量級服務(wù)
本文詳細(xì)講解了使用VS2022在ASP.NET?Core中構(gòu)建輕量級服務(wù)的方法,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-12-12
asp.net上傳execl文件后,在頁面上加載顯示(示例代碼)
本篇文章主要是對asp.net上傳execl文件后,在頁面上加載顯示(示例代碼)進(jìn)行了介紹,需要的朋友可以過來參考下,希望對大家有所幫助2014-02-02
Asp.Mvc?2.0實現(xiàn)用戶注冊實例講解(1)
這篇文章主要介紹了Asp.Mvc?2.0如何實現(xiàn)用戶注冊,實例講解很細(xì)致,注冊功能是每個網(wǎng)站必不可少的組成部分,感興趣的的朋友可以參考下2015-08-08
解決 The Controls collection cannot be modified because the co
在.aspx或.ascx的如果包括%,并在.aspx, .ascs中使用了AjaxToolkit中的控件,那么很可能會引發(fā)這個問題,下面給出具體的解決方法。2010-10-10

