Net Core 三个常用的生命周期(transient/scope/singleton)

原文链接:https://www.cnblogs.com/ZkbFighting/p/12922029.html

1
2
3
4
5
6
7
AddTransient(shuan sen te)    瞬间生命周期   :  每次需要创建一个全新的
 
AddSigleton(Single ten)      单例进程唯一实例    :每一次请求都是同一个(多用于时间)
 
AddScoped(SiGao Pute)      作用域单例    :一个请求,一个实例;不同请求,不同实例。
 
一次的http请求 就是一个实例。

  AddSingleton:

1
2
3
4
//设定时区
           var timeid = Environment.GetEnvironmentVariable("TZ");
           VMSDateTime.TimeZoneId = timeid;
           services.AddSingleton<IVMSDateTime, VMSDateTime>();

  AddScoped:

1
2
//设置接口类
services.AddScoped<IAuthenticateService, TokenAuthenticationService>();services.AddScoped<IUserService, UserService>();services.AddScoped<Code.IProcessInterface, Code.Process>();services.AddScoped<Code.IBackendServiceBus, Code.BackendServiceBus>();

  节选自:原文 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
AddSingelton():
  顾名思义,AddSingleton()方法创建一个'Singleton'服务。
  首次请求时会创建'Singleton'服务。
  然后在后继的请求中都会使用相同的实例。
  因此,每个应用程序只创建一次'Singleton'服务,
  并且在整个应用程序声明周期中使用相同的该单个实例
 
AddScoped():
   此方法创建一个'Scoped'服务,在范围内每个请求中创建一个新的Scoped服务实例。
   例如,在web应用程序中,它为每个Http请求创建一个实例
   但是在同一Web请求中的其他服务在调用这个请求的时候,使用相同的实例。
   注意:它在一个客户端请求中是相同的,
          但在多个客户端请求中是不通的。
 
AddTransient():
    此方法创建一个'Transient'实例,每次请求的时候都会创建一个新的服务实例。

  

上面描述的比较抽象,不容易理解,用实例来讲解会比较直观。

下面通过具体的例子进行演示。
定义三个空的接口:IArticleService、IProductService、IUserService
然后定义三个实现:ArticleService、ProductService、UserService

1.将接口和实现注入到DI容器

在StartUp类的ConfigureServices方法添加下图代码

1
2
3
4
5
6
7
8
9
10
public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.Configure<Test>(Configuration.GetSection("Test"));
 
            //演示生命周期
            services.AddTransient<IUserService, UserService>();
            services.AddScoped<IArticleService, ArticleService>();
            services.AddSingleton<IProductService, ProductService>();
        }

  2.添加私有字段,在测试Controller:LifeTimeController中添加下图代码

1
2
3
4
5
6
private readonly IUserService _userService1;
        private readonly IUserService _userService2;
        private readonly IArticleService _articleService1;
        private readonly IArticleService _articleService2;
        private readonly IProductService _productService1;
        private readonly IProductService _productService2;

  3.添加构造方法

1
2
3
4
5
6
7
8
9
10
11
12
13
public LifeTimeController(
            IUserService userService1, IUserService userService2,
            IArticleService articleService1, IArticleService articleService2,
            IProductService productService1, IProductService productService2
        )
        {
            _userService1 = userService1;
            _userService2 = userService2;
            _articleService1 = articleService1;
            _articleService2 = articleService2;
            _productService1 = productService1;
            _productService2 = productService2;
        }

  4.添加测试代码

1
2
3
4
5
6
7
8
9
10
11
12
13
public IActionResult Index()
        {
            var sb = new StringBuilder();
            sb.Append("transient1:" + _userService1.GetHashCode() + "<br />");
            sb.Append("transient2:" + _userService2.GetHashCode() + "<br />");
            sb.Append("scope1:" + _articleService1.GetHashCode() + "<br />");
            sb.Append("scope2:" + _articleService2.GetHashCode() + "<br />");
            sb.Append("singleton1:" + _productService1.GetHashCode() + "<br />");
            sb.Append("singleton2:" + _productService2.GetHashCode() + "<br />");
             
            Response.ContentType = "text/html";
            return Content(sb.ToString());
        }

  

5.执行结果

第一次刷新:

transient1:66454027
transient2:35021870
scope1:38350037
scope2:38350037
singleton1:4417230
singleton2:4417230

第二次刷新:

transient1:103653
transient2:5079042
scope1:47546512
scope2:47546512
singleton1:4417230
singleton2:4417230

可见

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

 

posted @   yinghualeihenmei  阅读(356)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2023-06-28 从数据类型 varchar 转换为 numeric 时出错
2023-06-28 根据时间段计算工作日的天数(SqlServer),包含节假日的处理
点击右上角即可分享
微信分享提示