Detailed explanation ASP.NET Framework level dependency injection in core

Time:2020-11-23

1、 ASP.NET Dependency injection in core

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

  1. Singleton – always returns the same instance
  2. Transient – returns a new instance each time
  3. Scoped – returns the same instance in the current (request) scope

Suppose we have two artifacts to work through dependency injection:

  1. Pagecontext – custom request context
  2. Settings – global application settings

Both are very simple classes. The pagecontext class provides the title label of 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. Registration dependency

Before using these classes in UI building blocks, you need to register them at application startup. 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 controllers and other UI components that support dependency injection.

3. Inject instance into 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. Injecting instances into a view

Now that the page title is assigned to the action of the controller, it’s time to use the title in the layout page. I added a title to the content area of the page, so in the tech.io It’s also easy to see in the environment. To be able to use pagecontext in layout pages, I used view injection (the first line in the code snippet below).


@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

ASP.NET Dependency injection in 5 (Gunnar peipman)
ASP.NET Core: using view injection (Gunnar peipman)

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.