ASP.NET Core MVC's dependency injection View

  ASP.NET Core support in trying to use dependency injection. This view will help provide specific services, such as localized or only data used to populate the view element. Should keep the separation of concerns between the controller and the view. Most of the data displayed view should be passed from the controller.

  Use @Inject service instruction is injected into the view, the syntax @inject <type> <name>, for example:

@model MVCTest.Models.Operation
@using MVCTest.Services
@inject BaseInfoServices BaseInfoServices

@{
    ViewData["Title"] = "Create";
}
<ul>
    @foreach (var city in BaseInfoServices.GetCities())
    {
    <li>@city</li>
    }
</ul>
    public class BaseInfoServices
    {
        public List<string> GetCities()
        {
            return new List<string>();
        }
    }

  ConfigureServices configured in advance, added to the service container.

 

  1. Find padding data

  Facilitate the injection filling view UI elements such as drop-down list box. For example, a gender, state, and other forms of user data. If you render this form by standard MVC, you'll need a controller for each set of options are requesting data access service, and then filled into the model or options ViewBag each group binding.

  Another service is directly injected into the view data for these options. This method will reduce to a minimum the amount of the controller code, the logical view of the elements is configured to move the view itself. Action controller simply pass a user profile data to form.

  

  2. Rewrite Service

  In addition to injecting services, this technology can also be used to override the page previously injected into the service. For example, replace the default HTML Helper:

@model MVCTest.Models.Operation
@using MVCTest.Services
@inject BaseInfoServices BaseInfoServices
@inject MyHtmlHelper Html

  Use @Html in the view will call the service custom.

  If you want to extend existing services rather than replace, you only need to use this technology, so that the service can be inherited or package has been achieved.

 

Guess you like

Origin www.cnblogs.com/afei-24/p/11366373.html