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


AddTransient(shuan sen te)    瞬間生命周期   :  每次需要創建一個全新的

AddSigleton(Single ten)      單例進程唯一實例    :每一次請求都是同一個(多用於時間)

AddScoped(SiGao Pute)      作用域單例    :一個請求,一個實例;不同請求,不同實例。

一次的http請求 就是一個實例。

AddSingleton:

 //設定時區
            var timeid = Environment.GetEnvironmentVariable("TZ");
            VMSDateTime.TimeZoneId = timeid;
            services.AddSingleton<IVMSDateTime, VMSDateTime>();

AddScoped:

//設置接口類

services.AddScoped<IAuthenticateService, TokenAuthenticationService>();
services.AddScoped<IUserService, UserService>();
services.AddScoped<Code.IProcessInterface, Code.Process>();
services.AddScoped<Code.IBackendServiceBus, Code.BackendServiceBus>();

 

節選自:原文 

AddSingelton():
  顧名思義,AddSingleton()方法創建一個'Singleton'服務。
  首次請求時會創建'Singleton'服務。
  然后在后繼的請求中都會使用相同的實例。
  因此,每個應用程序只創建一次'Singleton'服務,
  並且在整個應用程序聲明周期中使用相同的該單個實例

AddScoped():
   此方法創建一個'Scoped'服務,在范圍內每個請求中創建一個新的Scoped服務實例。
   例如,在web應用程序中,它為每個Http請求創建一個實例
   但是在同一Web請求中的其他服務在調用這個請求的時候,使用相同的實例。
   注意:它在一個客戶端請求中是相同的,
          但在多個客戶端請求中是不通的。

AddTransient():
    此方法創建一個'Transient'實例,每次請求的時候都會創建一個新的服務實例

 

上面描述的比較抽象,不容易理解,用實例來講解會比較直觀。

下面通過具體的例子進行演示。
定義三個空的接口:IArticleService、IProductService、IUserService
然后定義三個實現:ArticleService、ProductService、UserService

1.將接口和實現注入到DI容器

在StartUp類的ConfigureServices方法添加下圖代碼

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中添加下圖代碼

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.添加構造方法

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.添加測試代碼

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類型的生命周期,每次請求都是一樣的

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM