.Net 6 + WebApi Basics 9 - Lifetimes for Dependency Injection
2023-01-25 23:02:53  .Net  >> .Net6  >> WebApi

Types of Lifetime for Dependency Injection

When a service requests from another service via DI, generally in IOC, it is important to know whether the object received is the new instance or an existing instance. Thus, ASP.NET gives three options to request different types of service object.

There are three types of lifetime for dependency injection(DI) in .NET 6:
Transient, Scoped, and Singleton.

They define the lifetime of services created using DI.

Transient

The transient service always create one NEW instance to EVERY request, and EVERY controller and EVERY service within the request, which means no matter what to use will have a different instance to use.

Simply put, you have planned to have 10 meetings today in the meeting room, then 10 different persons come in and go out.

Scoped

The scoped service create ONE instance for EVERY request, and the same instance is used thoughout this request process, which means the controllers or services within this request will use same instance.

Simply put, you have planned to have 10 meetings today in the meeting room, then only 1 person come in and go out.

Singleton

The singleton service create ONE instance for FIRST request, and the same instance is used for all requests.

Simply put, you have planned to have 10 meetings today in the meeting room, then only 1 person come in and stay in the room, and go out after finishing the 10 meetings.

Lifetime Analysis

Performance

The time of creating new instance can determine the perfomance.

Singleton > Scoped > Transient

Singleton creates the service instance only once, so performance is the best.

Transient creates a different instance for everythin and has the worst performance.

Rebustness

Thread safety is an indicator of robustness.

Singleton < Scoped < Transient

Transient uses a different instance for each request, controller, and service, and there is no risk that the service being used will be modified in the middle of the process.

Singleton uses only one instance. Once the instance is modified, it will affect the whole process.

Resource Releases

.NET has a pretty fancy mechanism for garbage collection, but it is still better to have fewer time of using garbage collector.

Singleton < Scoped < Transient

Transient will release the resources once any request, controllers, or services is used up, while Singleton is still there when it is used up and not released.

Frequency of Use

Transient = Scoped > Singleton

Even though Singleton has better performance, for better robustness in the real-life use, Transient and Scoped are mostly used in development, and Singleton is rarely used.

References

Microsoft

Stackoverflow


Next: .Net6 + WebApi Basics 10.Net6 + WebApi Basics 10

Last: .Net 6 + WebApi Basics 8


Good Day
😎