Service life cycle in Ioc


I. Introduction

I wrote a blog earlier about Ioc inversion of control.
In that article, I mainly introduced the idea of ​​Ioc and its common implementation - Dependency Injection (DI) , and then demonstrated the use of Microsoft.Extensions.DependencyInjection (this should be counted as the DI package that comes with .NET).

However, the use of DI is just a simple demonstration process without in-depth study. This article further studies on the service .


2. Service life cycle

2.1 Service life cycle

Why learn from the service life cycle?
Because when I add elements to the service collection (ServiceCollection), I found that there are three methods:
AddScoped(), AddSingleton(), AddTransient().
They represent range/scope, singleton, and transient respectively, and these three methods correspond to the three fields in the ServiceLifetime enumeration.

    public enum ServiceLifetime
    {
    
    
        //
        // 摘要:
        //    将服务创建为单例
        Singleton,
        //
        // 摘要:
        //     为每个作用域创建新的服务实例
        //
        // 言论:
        //     In ASP.NET Core applications a scope is created around each server request.
        Scoped,
        //
        // 摘要:
        //		每次都会创建一个新实例
        //             //     requested.
        Transient
    }
Singleton
Objects are created only once throughout the application life cycle and all requests share this instance. Applicable to globally shared resources or services, such as configuration, cache, etc.
Scoped
In the same scope, the object will only be created once, and all requests will share this instance. When the scope ends, the object is destroyed. It is suitable for scenarios that need to share state within a request cycle.
Transient
Each request creates a new object instance, independent of each other. Suitable for stateless services or short-lived objects.

These policies help control resource usage and improve application performance.

2.2 Status

"Status" here refers to theData or information held and maintained by an object during its lifetime. A state can be an attribute or field value of an object that describes the state of the object at a specific point in time. A stateful object changes during its lifetime, while a stateless object remains unchanged throughout its lifetime. In the context of dependency injection, choosing an appropriate lifecycle management strategy (Scoped, Singleton, Transient) can ensure that objects maintain their state correctly during their lifetime.

2.3 Expansion: application scenarios of static classes and singletons

Speaking of status, let's expand it further.

It is said above that stateless objects remain unchanged throughout their lifetime. A typical example is a calculator class. A calculator class can contain methods for performing basic mathematical operations such as addition, subtraction, multiplication, and division, but it does not store any data associated with these operations. Every time the calculator method is called, it only needs to perform the corresponding calculation according to the parameters passed in and return the result without maintaining or modifying any internal state (of course, there are also calculators with historical records, which will modify their state after calculation, But this is not discussed here). Therefore, the calculator class is stateless and can be shared and reused across multiple requests without side effects or race conditions.

For stateless classes, you can use static classes or the singleton pattern, depending on your needs and design goals.

Static class (static class) :
Methods and properties in a static class are static, which means you can access them directly without creating an instance of the class. Static classes are good for utility methods or functions that don't need to maintain state, like math calculations, string manipulation, etc. Static members of static classes are only created and initialized once, and then shared throughout the application, so they save memory usage.
Singleton mode :
The singleton pattern ensures that a class has only one instance in the program and provides a global point of access. It is suitable for situations where state needs to be maintained but the state can be shared across the application. While the singleton pattern can also be used with stateless classes, usually static classes are simpler and more efficient.

For stateless classes, static classes are usually a better choice because they are simple, efficient, and easy to use.

3. Summary

In Ioc,

  • Singleton is used to create only once in the entire application life cycle, and each request is the same instance;
  • Scoped is only created once in the same scope;
  • Transient is a new instance for each request;
  • State is the data or information that an object maintains and maintains during its lifetime;
  • Stateless classes are often implemented with static classes.

Guess you like

Origin blog.csdn.net/BadAyase/article/details/130558187