Detailed explanation of framework level dependency injection in ASP. NET Core

  • 2021-10-15 10:16:34
  • OfStack

1. Dependency injection in ASP. NET Core

This example shows how framework-level dependency injection works in ASP. NET Core. It is simple but powerful enough to do most of the dependency injection work. Framework-level dependency injection supports the following scope:

Singleton-Always returns the same instance Transient--Returns a new instance each time Scoped-Returns the same instance in the current (request) range

Suppose we have two artifacts to work with dependency injection:

PageContext-Custom Request Context Settings-Global Application Settings

These are both very simple classes. The PageContext class provides a title label for the current page title for the layout page.


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. Register dependencies

Before you can use these classes in the UI building block, you need to register them at application startup time. This can be done in the ConfigureServices () method of the Startup class.


public void ConfigureServices(IServiceCollection services)
{
  services.AddMvc();
  var settings = new Settings();
  settings.SiteName = Configuration["SiteName"];
  services.AddSingleton(settings);
  services.AddScoped<PageContext>();
}

You can now inject these classes into dependency injection-enabled controllers and other UI components.

3. Inject instances into the controller

We assign page titles through the PageContext class in the Home controller.


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();
  }
}

This is a good way to assign page titles, because we don't have to use ViewData, which makes it easier to support multilingual applications.

4. Inject instances into the view

Now that page titles are assigned in the controller's action, it's time to use them in the layout page. I've added a title to the content area of the page, so it's also easy to see in the tech. io environment. In order to use PageContext in the layout page, I used view injection (line 1 in the following code snippet).


@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" rel="external nofollow" />
    <link rel="stylesheet" href="~/css/site.css" rel="external nofollow" />
  </environment>
  <environment names="Staging,Production">
    <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow" 
       asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css" rel="external nofollow" 
       asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
    <link rel="stylesheet" href="~/css/site.min.css" rel="external nofollow" asp-append-version="true" />
  </environment>
</head>
...
</html>

5. Reference materials

Dependency injection in ASP. NET 5 (Gunnar Peipman)
ASP. NET Core: Using view injection (Gunnar Peipman)


Related articles: