前言
ASP.NET Core MVC 控制器通過建構式顯式請求依賴關系,ASP.NET Core 內置有對依賴關系注入 (DI) 的支持,DI 使應用更易于測驗和維護,
建構式注入
服務作為建構式引數添加,并且運行時從服務容器中決議服務, 通常使用介面來定義服務, 例如,考慮需要當前時間的應用, 以下介面公開 IDateTime 服務:
public interface IDateTime{DateTime Now { get; }}
以下代碼實作 IDateTime 介面:
public class SystemDateTime : IDateTime{public DateTime Now{get { return DateTime.Now; }}}
將服務添加到服務容器中:
public void ConfigureServices(IServiceCollection services){services.AddSingleton<IDateTime, SystemDateTime>();services.AddControllersWithViews();}
以下代碼根據一天中的時間向用戶顯示問候語:
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();}
運行應用并且系統將根據時間顯示一條訊息,
FromServices的操作注入
FromServicesAttribute 允許將服務直接注入到操作方法,而無需使用建構式注入:
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; }}
將配置類添加到服務集合中:
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();}}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/227007.html
標籤:.NET技术
