Understanding of the three life cycles of. net core dependency injection

AddTransient mode: get a new instance for each request. Even if the same request gets multiple times, it will be different instances
(note that getting multiple objects here refers to getting objects through context rather than sharing the previous object)
AddScoped: get a new instance for each request. If the same request is obtained multiple times, the same instance will be obtained
AddSingleton singleton mode: get the same instance every time

 

Transient: kick God special
Scoped: death depends on attack
 
Let's explain the differences between the three.
 
 /*
     * Demonstrates an example of a dependency injection lifecycle
     */
    [Route("api/[controller]")]
    [ApiController]
    public class DIDemoController : ControllerBase
    {
        private readonly IBlogNewsService _blogNewsService;
        public DIDemoController(IBlogNewsService blogNewsService)
        {
            _blogNewsService = blogNewsService;
        }


        /// <summary>
        ///The instance object is called multiple times in a method
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetBlogNews2")]
        public async Task<IActionResult> GetBlogNews2()
        {
            var data = await _blogNewsService.QueryAsync();

            //Perform the second pass
            var data2 = await _blogNewsService.QueryAsync();

            //Test conclusion: no matter which injection method, in the same http request_ blogNewsService is the same object, because this is the same object_ blogNewsService, ha ha
            //Only when AddSingleton is injected_ The blogNewsService instance will only be instantiated once in the system, and other subsequent http requests will not be instantiated because it is a singleton
            //During AddTransient injection and AddScoped injection, each http request will be re instantiated_ blogNewsService!!!!
            return new JsonResult(new
            {
                first = "First instance:" + _blogNewsService.GetHashCode(),
                seconed = "Second instance:" + _blogNewsService.GetHashCode(),
            });
        }


        /// <summary>
        ///Getting multiple instance objects in the same method
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetBlogNews3")]
        public async Task<IActionResult> GetBlogNews3()
        {
            //Instance_ blogNewsService
            var data = await _blogNewsService.QueryAsync();


            //Retrieve an instance new_blogNewsService
            IBlogNewsService new_blogNewsService = HttpContext.RequestServices.GetService(typeof(IBlogNewsService)) as IBlogNewsService;
            var data2 = await new_blogNewsService.QueryAsync();

            //Test conclusion: during AddTransient injection, when the same http request_ blogNewsService and new_blogNewsService is not the same object. For different http requests_ blogNewsService and new_blogNewsService is not the same object.
            //During AddScoped injection, when the same http request_ blogNewsService and new_blogNewsService is the same object. Different http requests_ blogNewsService and new_blogNewsService is also the same object, but it is not an instance with another http request
            //During AddSingleton injection_ blogNewsService and new_blogNewsService is the same object. No matter which http interface it is, there is only one instance in the whole system.
            return new JsonResult(new
            {
                first = "First instance:" + _blogNewsService.GetHashCode(),
                seconed = "Second instance:" + new_blogNewsService.GetHashCode(),
            });
        }
    }

  

 //The following tests the lifecycle of dependency injection
            
            /*
            services.AddScoped<IBlogNewsRepository, BlogNewsRepository>();
            services.AddScoped<IBlogNewsService, BlogNewsService>();
            //*/
            
            services.AddTransient<IBlogNewsRepository, BlogNewsRepository>();
            services.AddTransient<IBlogNewsService, BlogNewsService>();
            //*/
            /*
            services.AddSingleton<IBlogNewsRepository, BlogNewsRepository>();
            services.AddSingleton<IBlogNewsService, BlogNewsService>();
            //*/
          

 

Test results:
1. AddSingleton needless to say, the singleton mode of the whole system is the same instance object.
 
2. AddScoped injection mode
(1) First, access GetBlogNews2 for the first time
 
{ "first": "First instance:35835861", "seconed": "Second instance:35835861" }

  

(2) Visit GetBlogNews2 again
{ "first": "First instance:10479095", "seconed": "Second instance:10479095" }

  

It is concluded that the object injected through AddScoped in the same request is the same instance when the object is used multiple times. (in fact, it's easy to understand that this is the same object _blogNewsService, which is just called many times)
For different requests, the object injected through AddScoped is the same instance when the object is used multiple times. But for different http requests, the instances of the two objects are different.
 
(3) First visit GetBlogNews3 for the first time
{ "first": "First instance:66980443", "seconed": "Second instance:66980443" }

  

(4) Visit GetBlogNews3 again
{ "first": "First instance:53734993", "seconed": "Second instance:53734993" }

  

It is concluded that the object injected through AddScoped in the same request is the same instance when the object is used multiple times.
For different requests, the object injected through AddScoped is the same instance when the object is used multiple times. But for different http requests, the instances of the two objects are different.
 
3. AddTransient injection mode
(1) First, access GetBlogNews2 for the first time
{ "first": "First instance:6451435", "seconed": "Second instance:6451435" }

  

(2) Visit GetBlogNews2 again
{ "first": "First instance:49538252", "seconed": "Second instance:49538252" }

  

It is concluded that the object injected through AddTransient in the same request is the same instance when the object is used multiple times. (in fact, it's easy to understand that this is the same object _blogNewsService, which is just called many times)
For different requests, the object injected through AddTransient is the same instance when the object is used multiple times. But for different http requests, the instances of the two objects are different.
 
(3) First visit GetBlogNews3 for the first time
{ "first": "First instance:2681320", "seconed": "Second instance:5135072" }

  

(4) Visit GetBlogNews3 again
{ "first": "First instance:59817589", "seconed": "Second instance:48209832" }

  

It is concluded that the object injected through AddTransient in the same request is a new instance when the injected object is retrieved.
For different requests, the object injected through AddTransient is a new instance when the injected object is retrieved.

Keywords: .NET

Added by lindm on Sat, 08 Jan 2022 08:01:36 +0200