依賴注入和控制器


依賴注入和控制器

原文: Dependency Injection and Controllers
作者: Steve Smith
翻譯: 劉浩楊
校對: 孟帥洋(書緣)

ASP.NET Core MVC 控制器應通過它們的構造器明確的請求它們的依賴關系。在某些情況下,單個控制器的操作可能需要一個服務,在控制器級別上的請求可能沒有意義。在這種情況下,你也可以選擇將服務作為 action 方法的參數。

章節:

查看或下載示例代碼

 

依賴注入

依賴注入(Dependency injection,DI)是一種如 Dependency Inversion Principle 所示的技術,允許應用程序由松散耦合的模塊組成。ASP.NET Core 內置了 dependency injection,這使得應用程序更容易測試和維護。

 

構造器注入

ASP.NET Core 內置的基於構造器的依賴注入支持擴展到 MVC 控制器。通過只添加一個服務類型作為構造器參數到你的控制器中,ASP.NET Core 將會嘗試使用內置的服務容器解析這個類型。服務通常是,但不總是使用接口來定義。例如,如果你的應用程序存在取決於當前時間的業務邏輯,你可以注入一個檢索時間的服務(而不是對它硬編碼),這將允許你的測試通過一個使用設置時間的實現。

復制代碼
using System; namespace ControllerDI.Interfaces { public interface IDateTime { DateTime Now { get; } } }
 

實現這樣一個接口,它在運行時使用的系統時鍾是微不足道的:

復制代碼
using System; using ControllerDI.Interfaces; namespace ControllerDI.Services { public class SystemDateTime : IDateTime { public DateTime Now { get { return DateTime.Now; } } } }
 

有了這些代碼,我們可以在我們的控制器中使用這個服務。在這個例子中,我們在 HomeController 的 Index 方法中加入一些根據一天中的時間向用戶顯示問候的邏輯。

復制代碼
using ControllerDI.Interfaces; using Microsoft.AspNetCore.Mvc; namespace ControllerDI.Controllers { public class HomeController : Controller { private readonly IDateTime _dateTime; //手動高亮 public HomeController(IDateTime dateTime) //手動高亮 { _dateTime = dateTime; //手動高亮 } public IActionResult Index() { var serverTime = _dateTime.Now; //手動高亮 if (serverTime.Hour < 12) //手動高亮 { ViewData["Message"] = "It's morning here - Good Morning!"; //手動高亮 } else if (serverTime.Hour < 17) //手動高亮 { ViewData["Message"] = "It's afternoon here - Good Afternoon!"; //手動高亮 } else //手動高亮 { ViewData["Message"] = "It's evening here - Good Evening!"; //手動高亮 } return View(); //手動高亮 } } }
 

如果我們現在運行應用程序,我們將可能遇到一個異常:

復制代碼
An unhandled exception occurred while processing the request. InvalidOperationException: Unable to resolve service for type 'ControllerDI.Interfaces.IDateTime' while attempting to activate 'ControllerDI.Controllers.HomeController'. Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
 

這個錯誤發生時,我們沒有在我們的 Startup 類的 ConfigureServices 方法中配置服務。要指定請求 IDateTime 時使用 SystemDateTime 的實例來解析,添加下面的清單中高亮的行到你的 ConfigureServices 方法中:

復制代碼
public void ConfigureServices(IServiceCollection services) { // Add application services. services.AddTransient<IDateTime, SystemDateTime>(); //手動高亮 }
 

注意
這個特殊的服務可以使用任何不同的生命周期選項來實現(TransientScoped或 Singleton)。參考 dependency injection 來了解每一個作用域選項將如何影響你的服務的行為。

一旦服務被配置,運行應用程序並且導航到首頁應該顯示預期的基於時間的消息:

提示
參考 Testing Controller Logic 學習如何在控制器中顯示請求依賴關系http://deviq.com/explicit-dependencies-principle 讓代碼更容易測試。

ASP.NET Core 內置的依賴注入支持用於請求服務的類型只有一個構造器。如果你有多於一個構造器,你可能會得到一個異常描述:

復制代碼
An unhandled exception occurred while processing the request. InvalidOperationException: Multiple constructors accepting all given argument types have been found in type 'ControllerDI.Controllers.HomeController'. There should only be one applicable constructor. Microsoft.Extensions.DependencyInjection.ActivatorUtilities.FindApplicableConstructor(Type instanceType, Type[] argumentTypes, ConstructorInfo& matchingConstructor, Nullable`1[]& parameterMap)
 

作為錯誤消息狀態,你可以糾正只有一個構造器的問題。你也可以參考 replace the default dependency injection support with a third party implementation 支持多個構造器。

 

Action 注入和 FromServices

有時候在你的控制器中你不需要為超過一個 Action 使用的服務。在這種情況下,將服務作為 Action 方法的一個參數是有意義的。這是通過使用特性 [FromServices] 標記參數實現,如下所示:

復制代碼
public IActionResult About([FromServices] IDateTime dateTime) //手動高亮 { ViewData["Message"] = "Currently on the server the time is " + dateTime.Now; return View(); }
 
 

從控制器訪問設置

在控制器中訪問應用程序設置或配置設置是一個常見的模式。此訪問應當使用在 configuration 所描述的訪問模式。你通常不應該從你的控制器中使用依賴注入直接請求設置。更好的方式是請求 IOptions<T> 實例, T 是你需要的配置類型。

要使用選項模式,你需要創建一個表示選項的類型,如:

復制代碼
namespace ControllerDI.Model { public class SampleWebSettings { public string Title { get; set; } public int Updates { get; set; } } }
 

然后你需要配置應用程序使用選項模型,在 ConfigureServices 中添加你的配置類到服務集合中:

復制代碼
public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() //手動高亮 .SetBasePath(env.ContentRootPath) //手動高亮 .AddJsonFile("samplewebsettings.json"); //手動高亮 Configuration = builder.Build(); //手動高亮 } public IConfigurationRoot Configuration { get; set; } //手動高亮 // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { // Required to use the Options<T> pattern services.AddOptions(); //手動高亮 // Add settings from configuration services.Configure<SampleWebSettings>(Configuration); //手動高亮 // Uncomment to add settings from code //services.Configure<SampleWebSettings>(settings => //{ // settings.Updates = 17; //}); services.AddMvc(); // Add application services. services.AddTransient<IDateTime, SystemDateTime>(); }
 

注意
在上面的清單中,我們配置應用程序程序從一個 JSON 格式的文件中讀取設置。你也可以完全在代碼中配置設置,像上面的代碼中所顯示的。參考 configuration 更多的配置選項。

一旦你指定了一個強類型的配置對象(在這個例子中,SampleWebSettings),並且添加到服務集合中,你可以從任何控制器或 Action 方法中請求 IOptions<T> 的實例(在這個例子中, IOptions<SampleWebSettings>)。下面的代碼演示了如何從控制器中請求設置。

復制代碼
    public class SettingsController : Controller { private readonly SampleWebSettings _settings; //手動高亮 public SettingsController(IOptions<SampleWebSettings> settingsOptions) //手動高亮 { _settings = settingsOptions.Value; //手動高亮 } public IActionResult Index() { ViewData["Title"] = _settings.Title; ViewData["Updates"] = _settings.Updates; return View(); } }
 

遵循選項模式允許設置和配置互相分離,確保控制器遵循 separation of concerns ,因為它不需要知道如何或者在哪里找到設置信息。由於沒有 static cling 或在控制器中直接實例化設置類,這也使得控制器更容易單元測試 。

返回目錄

由於水平有限,錯漏之處在所難免,歡迎大家批評指正,不勝感激,我們將及時修正。
dotNet Core Studying Group:436035237
 
分類:  ASP.NET CORE


免責聲明!

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



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