在 ASP.NET Core 中將依賴項注入到控制器

前言

ASP.NET Core MVC 控制器經過構造函數顯式請求依賴關係。ASP.NET Core 內置有對依賴關係注入 (DI) 的支持。DI 使應用更易於測試和維護。javascript

構造函數注入

服務做爲構造函數參數添加,而且運行時從服務容器中解析服務。 一般使用接口來定義服務。 例如,考慮須要當前時間的應用。 如下接口公開 IDateTime 服務:java

 

public interface IDateTime{DateTime Now { get; }}

如下代碼實現 IDateTime 接口:web

public class SystemDateTime : IDateTime{public DateTime Now{get { return DateTime.Now; }}}

將服務添加到服務容器中:typescript

public void ConfigureServices(IServiceCollection services){services.AddSingleton<IDateTime, SystemDateTime>();services.AddControllersWithViews();}

如下代碼根據一天中的時間向用戶顯示問候語:json


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();}

運行應用而且系統將根據時間顯示一條消息。ruby

FromServices的操做注入

FromServicesAttribute 容許將服務直接注入到操做方法,而無需使用構造函數注入:less

public IActionResult About([FromServices] IDateTime dateTime){return Content( $"Current server time: {dateTime.Now}");}

從控制器訪問設置

從控制器中訪問應用或配置設置是一種常見模式。ASP.NET Core 中的選項模式 中所述的選項模式是管理設置的首選方法 。 一般狀況下,不直接將 IConfiguration 注入到控制器。函數

建立表示選項的類。 例如:測試

public class SampleWebSettings{public string Title { get; set; }public int Updates { get; set; }}

將配置類添加到服務集合中:ui

public void ConfigureServices(IServiceCollection services){services.AddSingleton<IDateTime, SystemDateTime>();services.Configure<SampleWebSettings>(Configuration);services.AddControllersWithViews();}

將應用配置爲從 JSON 格式文件中讀取設置:

public class Program{public static void Main(string[] args){CreateHostBuilder(args).Build().Run();}public static IHostBuilder CreateHostBuilder(string[] args) =>Host.CreateDefaultBuilder(args).ConfigureAppConfiguration((hostingContext, config) =>{config.AddJsonFile("samplewebsettings.json",optional: false,reloadOnChange: true);}).ConfigureWebHostDefaults(webBuilder =>{webBuilder.UseStartup<Startup>();});}

如下代碼從服務容器請求 IOptions<SampleWebSettings> 設置,並經過 Index 方法使用它們:


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();}}
相關文章
相關標籤/搜索