ASP.NET Core 服务的生命周期

发布时间 2023-09-19 16:23:25作者: 说不出来

概念

Transient:每一次GetService都会创建一个新的实例

Scoped:在同一个Scope内只初始化一个实例 ,可以理解为 每一个request级别只创建一个实例,同一个http request会在一个 scope内

Singleton:整个应用程序生命周期内只创建一个实例

案例演示

1.定义三个空的接口:IArticleService、IProductService、IUserService
然后定义三个实现:ArticleService、ProductService、UserService
接口和类都定义为空,不包含字段和方法

2.webapi下依赖注入添加对应的接口和类

namespace LifeCycleTest
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.

            builder.Services.AddControllers();
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();
            //演示生命周期
            builder.Services.AddTransient<IUserService, UserService>();
            builder.Services.AddScoped<IArticleService, ArticleService>();
            builder.Services.AddSingleton<IProductService, ProductService>();
            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            app.UseHttpsRedirection();

            app.UseAuthorization();


            app.MapControllers();

            app.Run();
        }
    }
}

3.定义接口获取Hash Code

using Microsoft.AspNetCore.Mvc;
using System.Text;

namespace LifeCycleTest.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class LifeController : ControllerBase
    {
        private readonly IUserService _userService1;
        private readonly IUserService _userService2;
        private readonly IArticleService _articleService1;
        private readonly IArticleService _articleService2;
        private readonly IProductService _productService1;
        private readonly IProductService _productService2;

        public LifeController(
            IUserService userService1, IUserService userService2,
            IArticleService articleService1, IArticleService articleService2,
            IProductService productService1, IProductService productService2
        )
        {
            _userService1 = userService1;
            _userService2 = userService2;
            _articleService1 = articleService1;
            _articleService2 = articleService2;
            _productService1 = productService1;
            _productService2 = productService2;
        }

        [HttpGet]
        public string Test()
        {
            var sb = new StringBuilder();
            sb.Append("transient1:" + _userService1.GetHashCode() + Environment.NewLine);
            sb.Append("transient2:" + _userService2.GetHashCode() + Environment.NewLine);
            sb.Append("scope1:" + _articleService1.GetHashCode() + Environment.NewLine);
            sb.Append("scope2:" + _articleService2.GetHashCode() + Environment.NewLine);
            sb.Append("singleton1:" + _productService1.GetHashCode() + Environment.NewLine);
            sb.Append("singleton2:" + _productService2.GetHashCode() + Environment.NewLine);

            return sb.ToString();
        }
    }
}

4.运行后,刷新多次执行对比结果

可见
transient类型的生命周期,每次使用都不一样,不同的类或不同的方法使用都不一样
scope类型的生命周期,在同一个请求内是一样的
singleton类型的生命周期,每次请求都是一样的

asp.net core服务的生命周期 - 屌丝大叔的笔记 - 博客园 (cnblogs.com)

图片来源ASP.NET Core Service Lifetimes (Infographic) (ezzylearning.net)