Location>code7788 >text

.NetCore dependency injection (DI) life cycle

Popularity:7 ℃/2025-01-13 15:56:47

In .NET Core, Dependency Injection (DI) is a technology that implements Inversion of Control (IoC). It achieves communication between objects by injecting dependent objects into objects that need them. Decoupled. The dependency injection lifecycle determines how objects are created and managed in the application. There are three common life cycles:TransientScopedandSingleton


1. Transient

definition:

A new instance is created on every request.

Features:

  • A new object is created every time it is injected.
  • The object's lifetime is limited to the current request.
  • Suitable for lightweight, stateless services.

Usage scenarios:

  • Suitable for scenarios where each request requires an independent instance, such as tool classes, stateless services, etc.

Example:

public interface ITransientService
{
    Guid GetOperationId();
}

public class TransientService : ITransientService
{
    private readonly Guid _operationId;

    public TransientService()
    {
        _operationId = ();
    }

    public Guid GetOperationId() => _operationId;
}

existRegister in:

public void ConfigureServices(IServiceCollection services)
{
    <ITransientService, TransientService>();
}

Use in controller:

public class HomeController : Controller
 {
 Private readonly ITransientService _transientService1;
 Private readonly ITransientService _transientService2;

 Public HomeController(ITransientService transientService1, ITransientService transientService2)
 {
 ​ ​ _transientService1 = transientService1;
 ​ ​ _transientService2 = transientService2;
 }

 Public IActionResult Index()
 {
 ​ ​ _transientService1.DoWork();
 ​ ​ _transientService2.DoWork();

 ​​​​//Verify whether it is a different instance
 (_transientService1 == _transientService2); // Output: False

          return Ok();
 }
 }

Output:

Transient Service: Doing work...
    Transient Service: Doing work...
        False

2. Scoped

definition:

Within the same scope, the object is a singleton; but in different scopes, new instances will be created.

Features:

  • The object's lifetime is consistent with the requested scope.
  • Suitable for services that need to share state within request scope.

Usage scenarios:

  • Suitable for scenarios where state needs to be shared within request scope, such as database context, unit of work mode, etc.

Example:

public interface IScopedService
{
    void DoWork();
}

public class ScopedService : IScopedService
{
    public void DoWork()
    {
        ("Scoped Service: Doing work...");
    }
}

existRegister in

public void ConfigureServices(IServiceCollection services)
{
    <IScopedService, ScopedService>();
}

Use in controller:

public class HomeController : Controller
 {
 Private readonly IScopedService _scopedService1;
 Private readonly IScopedService _scopedService2;

 Public HomeController(IScopedService scopedService1, IScopedService scopedService2)
 {
 ​​​​​_scopedService1 = scopedService1;
 ​​​​​_scopedService2 = scopedService2;
 }

 Public IActionResult Index()
 {
 ​​​​​_scopedService1.DoWork();
 ​​​​​_scopedService2.DoWork();

 ​​​​//Verify whether it is the same instance
 (_scopedService1 == _scopedService2); // Output: True

          return Ok();
 }
 }

Output:

Scoped Service: Doing work...
    Scoped Service: Doing work...
        True

3. Singleton (single case)

definition:

Only one instance is created during the entire application life cycle.

Features:

  • The object's life cycle is consistent with the application's life cycle.
  • Suitable for globally shared services, such as configuration management, logging, etc.

Usage scenarios:

  • Suitable for scenarios that require global sharing, such as configuration management, caching, logging, etc.

Example:

public interface ISingletonService
{
    void DoWork();
}

public class SingletonService : ISingletonService
{
    public void DoWork()
    {
        ("Singleton Service: Doing work...");
    }
}

existRegister in:

public void ConfigureServices(IServiceCollection services)
{
    <ISingletonService, SingletonService>();
}

Use in controller:

public class HomeController : Controller
 {
 Private readonly ISingletonService _singletonService1;
 Private readonly ISingletonService _singletonService2;

 Public HomeController(ISingletonService singletonService1, ISingletonService singletonService2)
 {
 ​ ​ _singletonService1 = singletonService1;
 ​ ​ _singletonService2 = singletonService2;
 }

 Public IActionResult Index()
 {
 ​ ​ _singletonService1.DoWork();
 ​ ​ _singletonService2.DoWork();

 ​​​​//Verify whether it is the same instance
 (_singletonService1 == _singletonService2); // Output: True

          return Ok();
 }
 }

Output:

Singleton Service: Doing work...
Singleton Service: Doing work...
True

Summarize

life cycle definition Features Usage scenarios
Transient Create new instance on each request A new object is created every time it is injected Lightweight, stateless services, such as tools and stateless services
Scoped Within the same scope, objects are singletons The object's life cycle is consistent with the requested scope Services that require shared state within request scope, such as database contexts
Singleton Only one instance is created during the entire application life cycle The life cycle of the object is consistent with the life cycle of the application Globally shared services, such as configuration management and logging

By rationally choosing the life cycle of dependency injection, we can achieve flexible management and efficient use of objects, thereby improving the performance and maintainability of the application.