ASP.NET?Core?MVC控制器請求依賴注入
ASP.NET Core MVC 控制器應(yīng)通過構(gòu)造函數(shù)明確地請求它們地依賴關(guān)系,在某些情況下,單個控制器地操作可能需要一個服務(wù),在控制器級別上的請求可能沒有意義。在這種情況下,也可以將服務(wù)作為 Action 的參數(shù)。
依賴注入是一種如 Dependency Inversion Principle 所示的技術(shù),允許應(yīng)用程序松散耦合的模塊組成。
1.構(gòu)造函數(shù)注入
ASP.NET Core 內(nèi)置的基于構(gòu)造函數(shù)的依賴注入支持擴展到 MVC 控制器。通過只添加一個服務(wù)類型作為構(gòu)造函數(shù)參數(shù)到控制器中,ASP.NET Core 將會嘗試使用內(nèi)置服務(wù)容器解析這個類型。服務(wù)通常(但不總是)使用接口定義。例如,如果應(yīng)用程序定義一個檢索時間的服務(wù),然后依賴注入而不是硬編碼:
定義接口和實現(xiàn):
namespace MVCTest.Services { public interface IDateTime { DateTime Now { get; } } public class SystemDateTime: IDateTime { public DateTime Now { get { return DateTime.Now; } } } }
在 ConfigureServices 中注冊服務(wù)到容器:
services.AddTransient<IDateTime, SystemDateTime>();
在控制其中使用:
public class DateTimeController : Controller { private IDateTime _dateTime; public DateTimeController(IDateTime dateTime) { _dateTime = dateTime; } // GET: DateTime public ActionResult Index() { var serverTime = _dateTime.Now; if (serverTime.Hour < 12) { ViewData["Message"] = "Good Morning"; } return View(); } }
ASP.NET Core 內(nèi)置的依賴注入支持用于請求服務(wù)的類型只能有一個構(gòu)造函數(shù),如果多于一個會報異常。使用第三方實現(xiàn)替換默認依賴注入,可以實現(xiàn)支持多個構(gòu)造函數(shù)。
2.使用 FromServices 操作注入
有時,不需要在控制器為多個操作提供服務(wù)。在這種情況下,將服務(wù)注入到操作方法的參數(shù)是有意義的。通過 [FromServices] 標記參數(shù)來實現(xiàn):
public ActionResult Index([FromServices] IDateTime _dateTime) { var serverTime = _dateTime.Now; if (serverTime.Hour < 12) { ViewData["Message"] = "Good Morning"; } return View(); }
3.在控制器中訪問設(shè)置
在控制器中訪問應(yīng)用程序設(shè)置或者配置設(shè)置時常見的模式。此訪問應(yīng)當使用在 Configuration 中描述的訪問模式。通常不應(yīng)從控制器中使用依賴注入直接請求設(shè)置,更好的方式是請求 IOptions<T> 實例,T是你需要的配置類型。例如:
創(chuàng)建選項類:
public class AppSettingOptions { public DefaultConnec ConnectionStrings { get; set; } public string AllowedHosts { get; set; } } public class DefaultConnec { public string DefaultConnection { get; set; } }
appsettings.json:
{ "ConnectionStrings": { "DefaultConnection": "Data Source=.;Initial Catalog=Test;Integrated Security=True" }, "Logging": { "LogLevel": { "Default": "Information" } }, "AllowedHosts": "*" }
配置應(yīng)用程序使用選項模型,在 ConfigureServices 中添加配置類到服務(wù)容器:
public Startup(IConfiguration configuration,IHostingEnvironment env) { //Configuration = configuration; var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json",optional:true,reloadOnChange:true) //.AddJsonFile($"appsettings.{env.EnvironmentName}.json",optional:true) ; //配置環(huán)境變量 //builder.AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddOptions(); services.Configure<AppSettingOptions>(Configuration); //通過代碼編寫 services.Configure<AppSettingOptions>(options=> { options.AllowedHosts = "test"; }); }
示例是從 appsettings.json 讀取設(shè)置,也可以在代碼中添加設(shè)置。
一旦指定了請類型的配置對象 AppSettingOptions,并將其添加到服務(wù)容器,就可以在控制器或操作方法通過請求 IOptions<AppSettingOptions> 的實例獲取它:
public class HomeController : Controller { private readonly IOptions<AppSettingOptions> _options; public HomeController(IOptions<AppSettingOptions> options) { _options = options; } }
遵循選項模式允許將設(shè)置和配置彼此分離,并且確??刂破髯裱P(guān)注點分離,因為不需要知道如何在哪里找到設(shè)置信息。由于控制器類中沒有靜態(tài)附著或者直接實例化設(shè)置類,因此使得控制器更容易使用單元測試。
到此這篇關(guān)于ASP.NET Core MVC控制器請求依賴注入的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
asp.net音頻轉(zhuǎn)換之.amr轉(zhuǎn).mp3(利用七牛轉(zhuǎn)換法)
相信很多人都遇到amr格式的音頻文件不能直接在網(wǎng)頁播放的問題,有人使用QuickTime插件的輔助,下面這篇文章主要給大家介紹了asp.net音頻轉(zhuǎn)換之利用七牛轉(zhuǎn)換法將.amr格式轉(zhuǎn).mp3格式,需要的朋友可以參考借鑒,下面來一起看看吧。2016-12-12asp.net updatepanel 導致JS不能加載,而無法使用的解決方法
asp.net updatepanel 局部刷新,導致JS不能加載,而無法使用,而且 updatepanel會刷兩次,郁悶的,解決方法如下2013-08-08ASP.NET MVC解決上傳圖片臟數(shù)據(jù)的方法
這篇文章介紹了ASP.NET MVC解決上傳圖片臟數(shù)據(jù)的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-09-09asp.net中IDataParameter調(diào)用存儲過程的實現(xiàn)方法
這篇文章主要介紹了asp.net中IDataParameter調(diào)用存儲過程的實現(xiàn)方法,在asp.net數(shù)據(jù)庫程序設(shè)計中非常具有實用價值,需要的朋友可以參考下2014-09-09詳解Asp.Net Core 發(fā)布和部署( MacOS + Linux + Nginx )
這篇文章主要介紹了詳解Asp.Net Core 發(fā)布和部署( MacOS + Linux + Nginx ) ,具有一定的參考價值,有興趣的可以了解一下。2016-12-12