.Net Core Web Api_筆記34_服務生命週期解析

 

以下圖中Instance若背景色(深淺)
不同則代表不同獨立的Service Instance 物件實體


生命週期:
Transient:每次被請求都會創建新的實體
Transient objects are always different; a new instance is provided to every controller and every service.
通常針對比較輕量無狀態保存需求的服務很適合配置這類生命週期





Scoped:每次Web請求會創建一個新實體,直到web請求結束就銷毀。
Scoped objects are the same within a request, but different across different requests.

每一個請求都會建立一次獨立的服務物件實體,參與單一個請求中所有middleware,mvc控制器
通常會針對EFCore Context ,資料庫上下文的存取服務制定此生命週期





Singleton:一旦被創建實體就會持續一直用,直到應用停止才銷毀。
Singleton objects are the same for every object and every request.

被建立的服務類別會被存在內存當中,並於整個應用中被重複利用。
通常會針對物件實體化成本較高的服務配置為Singleton生命週期,讓他只初始化一次。



ServiceType ClassIn the capacityof same HttpRequestDifferent Http Request
AddSingletonThe same Instance of repository servedThe same Instance of repository served
AddScopedSame InstanceDifferent Instance
AddTransientEvery time New InstanceEvery time New Instance
































留言

這個網誌中的熱門文章

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header

經得起原始碼資安弱點掃描的程式設計習慣培養(三)_7.Cross Site Scripting(XSS)_Stored XSS_Reflected XSS All Clients

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題