在 ASP.NET Core 中将依赖项注入到控制器
前言
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();}}
原文转载:http://www.shaoqun.com/a/492978.html
贸发局:https://www.ikjzd.com/w/1621
网络星期一:https://www.ikjzd.com/w/80
adore:https://www.ikjzd.com/w/2202
前言ASP.NETCoreMVC控制器通过构造函数显式请求依赖关系。ASP.NETCore内置有对依赖关系注入(DI)的支持。DI使应用更易于测试和维护。构造函数注入服务作为构造函数参数添加,并且运行时从服务容器中解析服务。通常使用接口来定义服务。例如,考虑需要当前时间的应用。以下接口公开IDateTime服务:publicinterfaceIDateTime{DateTimeNow{get;}}
terapeak:terapeak
6pm:6pm
香港前水警总部酒店总汇三明治多少钱?什么时候结束?:香港前水警总部酒店总汇三明治多少钱?什么时候结束?
从深圳到惠东永记生态园怎么走?:从深圳到惠东永记生态园怎么走?
eBay与长沙高新区签署战略合作备忘录:eBay与长沙高新区签署战略合作备忘录