Default dependency injection for. NET

introduce

Collect coupons https://www.cps3.cn/

Do not rely on concrete implementation, but on abstraction. High-level modules should not rely on low-level modules. Both should rely on abstraction. In short, it is for better decoupling. Inversion of control (Ioc) is one of the implementation ideas of this principle. One of the implementation methods of this idea is dependency injection (DI). ASP.NET Core has built-in support for dependency injection (DI). Developers only need to define the interface in startup In the ConfigureServices method of CS, you can use the binding method corresponding to the life cycle.

As long as it is instantiated with new, there are dependencies.

life cycle

AddSingleton→AddTransient→AddScoped

Singleton (single case)

The service is created at the first request (or when we specify to create an instance and run the method in ConfigureServices), and each subsequent request will continue to use the created service. If the developer's application needs a singleton service scenario, it should be designed to allow the service container to operate the service life cycle, rather than manually implementing the singleton design pattern, and then the developer can operate in the user-defined class.

Picture from: https://blog.csdn.net/weixin_47498376/article/details/116177389

services.AddSingleton<IApplicationService,ApplicationService>

For example, some public classes

Scoped

From the beginning of a request to the end of the request, the objects obtained in this request are the same

Picture from: https://blog.csdn.net/weixin_47498376/article/details/116177389

services.AddScoped<IApplicationService,ApplicationService>

If the service is used many times in the process of a request and may share fields or attributes, use scoped, such as httpcontext (thanks for your help)

Transient

The object obtained each time is not the same, and it is best used for lightweight stateless services (such as our Repository and ApplicationService services)

Picture from: https://blog.csdn.net/weixin_47498376/article/details/116177389

services.AddTransient<IApplicationService,ApplicationService>

If the service is used only once in a request, it is good to register Transient.

Injection mode

    /// <summary>
    ///User interface
    /// </summary>
    public interface IUserService
    {
        string GetName();
    }

    /// <summary>
    ///User implementation
    /// </summary>
    public class UserService : IUserService
    {
        public string GetName()
        {
            return "AZRNG";
        }
    }

Injection is required in the ConfigureServices method

Constructor Inject

The service is added as a constructor parameter, and the runtime parses the service from the service container.

        private readonly IUserService _userService;

        public UserController(IUserService userService)
        {
            _userService = userService;
        }

        [HttpGet]
        public ActionResult GetName()
        {
            return Ok(_userService.GetName());
        }

FromServices operation injection

        [HttpGet]
        public ActionResult GetName([FromServices] IUserService _userService)
        {
            return Ok(_userService.GetName());
        }

core

Yes The core of DI in NET Core is divided into two components: IServiceCollection and IServiceProvider.

  • IServiceCollection is responsible for registration
  • IServiceProvider is responsible for providing instances
public void ConfigureServices(IServiceCollection services)
{
    //Limit the scope of the service life cycle to the life cycle of a single request
    services.AddTransient<IUserService, UserService>();
}

Get service

        private readonly IUserService _userService;
        public HomeController(IUserService userService)
        {
            _userService = userService;
        }

        public IActionResult Index()
        {
            var info = _userService.GetInfo();
            return View();
        }

IServiceProvider get

        private readonly IServiceProvider _service;
        public UserController(IServiceProvider service)
        {
            _service = service;
        }

        [HttpGet]
        public ActionResult GetName()
        {
            var _userService = (IUserService)_service.GetService(typeof(IUserService));
            return Ok(_userService.GetName());
        }

Get services from statrup

var provider = services.BuildServiceProvider();
var userserivce = provider.GetService<IUserService>();
//or
var userservice2 = provider.GetRequiredService<IUserService>();

WeChat official account

Added by chrisdee on Thu, 17 Feb 2022 14:53:04 +0200