怎么在ASP.NET Core 中注入框架依賴?很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
1、ASP.NET Core 中的依賴注入
此示例展示了框架級(jí)依賴注入如何在 ASP.NET Core 中工作。 其簡(jiǎn)單但功能強(qiáng)大,足以完成大部分的依賴注入工作??蚣芗?jí)依賴注入支持以下 scope:
Singleton — 總是返回相同的實(shí)例
Transient — 每次都返回新的實(shí)例
Scoped — 在當(dāng)前(request)范圍內(nèi)返回相同的實(shí)例
假設(shè)我們有兩個(gè)要通過依賴注入來進(jìn)行工作的工件:
PageContext — 自定義請(qǐng)求上下文
Settings — 全局應(yīng)用程序設(shè)置
這兩個(gè)都是非常簡(jiǎn)單的類。PageContext 類為布局頁(yè)面提供當(dāng)前頁(yè)面標(biāo)題的標(biāo)題標(biāo)簽。
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; } } }
2、注冊(cè)依賴
在 UI 構(gòu)建塊中使用這些類之前,需要在應(yīng)用程序啟動(dòng)時(shí)注冊(cè)這些類。該工作可以在 Startup 類的 ConfigureServices() 方法中完成。
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); var settings = new Settings(); settings.SiteName = Configuration["SiteName"]; services.AddSingleton(settings); services.AddScoped(); }
現(xiàn)在可以將這些類注入到支持依賴注入的控制器和其他 UI 組件中。
3、向控制器注入實(shí)例
我們通過 Home 控制器中的 PageContext 類分配頁(yè)面標(biāo)題。
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(); } }
這種分配頁(yè)面標(biāo)題的方式不錯(cuò),因?yàn)槲覀儾槐厥褂?ViewData,這樣更容易受支持多語言應(yīng)用程序支持。
4、向視圖注入實(shí)例
現(xiàn)在控制器的 action 中分配了頁(yè)面標(biāo)題,是時(shí)候在布局頁(yè)面中使用標(biāo)題了。 我在頁(yè)面的內(nèi)容區(qū)域添加了標(biāo)題,所以在 tech.io 環(huán)境中也很容易看到。為了能在布局頁(yè)面中使用到 PageContext,我使用了視圖注入(下面代碼片段中的第一行)。
@inject PageContext pageContext@pageContext.FullTitle ...
看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對(duì)創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司,的支持。