ASP.NET Core 中的框架級依賴注入

https://tech.io/playgrounds/5040/framework-level-dependency-injection-with-asp-net-core
做者: Gunnar Peipman
譯者:http://oopsguy.comcss

一、ASP.NET Core 中的依賴注入

本文將介紹 ASP.NET Core 框架級依賴注入是如何工做的。其簡單但功能強大,足以完成大部分依賴注入工做。框架級依賴注入支持如下 scope:html

  • Singleton — 老是返回相同的實例,單例
  • Transient — 每次都返回新的實例
  • Scoped — 在當前(request)範圍內返回相同的實例

假設咱們有兩個要經過依賴注入來進行工做的工件:ajax

  • PageContext — 自定義請求上下文
  • Settings — 全局應用程序設置

這兩個都是很是簡單的類。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>

五、參考材料

相關文章
相關標籤/搜索