https://tech.io/playgrounds/5040/framework-level-dependency-injection-with-asp-net-core
做者: Gunnar Peipman
译者:http://oopsguy.comcss
本文将介绍 ASP.NET Core 框架级依赖注入是如何工做的。其简单但功能强大,足以完成大部分依赖注入工做。框架级依赖注入支持如下 scope:html
假设咱们有两个要经过依赖注入来进行工做的工件:ajax
这两个都是很是简单的类。PageContext 类为布局页面提供当前页面标题的标题标签。bootstrap
public class Settings { public string SiteName; public string ConnectionString; } public class PageContext { private readonly Settings _settings; public PageContext(Settings settings) { _settings = settings; } public string PageTitle; public string FullTitle { get { var title = (PageTitle ?? "").Trim(); if(!string.IsNullOrWhiteSpace(title) && !string.IsNullOrWhiteSpace(_settings.SiteName)) { title += " | "; } title += _settings.SiteName.Trim(); return title; } } }
在 UI 构建块中使用这些类以前,你须要在应用程序启动时注册这些类。这些工做能够在 Startup 类的 ConfigureServices() 方法中完成。app
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); var settings = new Settings(); settings.SiteName = Configuration["SiteName"]; services.AddSingleton(settings); services.AddScoped<PageContext>(); }
如今能够将这些类注入到支持依赖注入的控制器和其余 UI 组件中。框架
咱们经过 Home 控制器中的 PageContext 类分配页面标题。asp.net
public class HomeController : Controller { private readonly PageContext _pageContext; public HomeController(PageContext pageContext) { _pageContext = pageContext; } public IActionResult Index() { _pageContext.PageTitle = ""; return View(); } public IActionResult About() { _pageContext.PageTitle = "About"; return View(); } public IActionResult Error() { _pageContext.PageTitle = "Error"; return View(); } }
这种分配页面标题的方式不错,由于咱们没必要使用 ViewData,这样更容易被支持多语言应用程序所支持。oop
如今控制器的 action 中分配了页面标题,是时候在布局页面中使用标题了。我在页面的内容区域添加了标题,因此在 tech.io 环境中也很容易看到。为了能在布局页面中使用到 PageContext,我使用了视图注入(如下代码片断中的第一行)。布局
@inject PageContext pageContext <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@pageContext.FullTitle</title> <environment names="Development"> <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" /> <link rel="stylesheet" href="~/css/site.css" /> </environment> <environment names="Staging,Production"> <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css" asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css" asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" /> <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" /> </environment> </head> ... </html>