在 C# 与 .NET 应用开发中,依赖注入不是简单的“把对象传进去”,而是一套围绕服务创建、共享和释放建立起来的运行时约定。生命周期配置决定了某个服务在整个应用、单个请求或单次解析中如何存在。理解 Transient、Scoped、Singleton 三种模式,可以帮助开发者在功能正确、资源占用和线程安全之间取得平衡。

三种生命周期的本质:实例创建与共享边界
Transient 可以理解为“每次解析都新建”。只要容器根据依赖关系解析该服务,就会生成一个新实例。即使同一个构造函数中连续解析两次同一个接口,得到的也不是同一个对象。这种模式适合无状态、创建成本低、不需要跨调用保持内存状态的服务,例如参数校验器、简单算法工具、一次性数据处理器等。它的优点是边界清晰,不容易因为共享状态产生副作用;代价是如果服务创建成本较高,频繁创建可能带来额外开销。
Scoped 的核心是“作用域内单例,作用域之间隔离”。在 Web 应用中,一个 HTTP 请求通常对应一个作用域,因此同一个请求内多次解析同一个 Scoped 服务会拿到同一个实例;当请求结束、作用域释放后,该实例也会随之进入可释放状态。下一个请求进来时,容器会为该请求创建新的 Scoped 实例。它特别适合那些需要绑定请求上下文、用户身份、数据库会话或请求级缓存的服务。
Singleton 则是“整个应用生命周期内只创建一个实例”。从应用启动开始,容器首次解析该服务时创建对象,之后无论来自哪个请求、哪个作用域、哪个组件,解析到的都是同一个对象。它适合配置读取、日志写入、全局缓存、外部客户端等需要长期复用且创建成本较高的服务。需要注意的是,Singleton 实例可能被多个请求并发访问,因此其内部状态必须保证线程安全,或者设计成无状态。
| 生命周期 | 实例边界 | 典型用途 | 需要注意 |
|---|---|---|---|
Transient | 每次解析创建新实例 | 无状态工具、校验器、轻量计算 | 避免高成本对象频繁创建 |
Scoped | 同一作用域内复用 | 数据库上下文、请求级缓存、工作单元 | 不要跨作用域长期持有 |
Singleton | 整个应用复用 | 配置、日志、全局缓存、外部客户端 | 必须考虑线程安全 |
在 .NET 中注册不同生命周期服务
在 .NET 的依赖注入容器中,生命周期通常通过 IServiceCollection 上的扩展方法表达。AddTransient、AddScoped、AddSingleton 三个方法分别对应三种生命周期。注册时一般把接口和实现类成对传入,这样上层代码只依赖接口,具体实现由容器负责创建和替换。
示例使用 ServiceCollection 直接注册并解析服务,不依赖 Web 环境,便于观察注册关系本身。示例中,Transient 服务被解析两次,Scoped 服务在同一个作用域内被解析两次,Singleton 服务在根提供程序中被解析两次。
using System;
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
// 注册三种不同生命周期的服务
services.AddTransient<ITransientService, TransientService>();
services.AddScoped<IScopedService, ScopedService>();
services.AddSingleton<ISingletonService, SingletonService>();
var provider = services.BuildServiceProvider();
var transient1 = provider.GetRequiredService<ITransientService>();
var transient2 = provider.GetRequiredService<ITransientService>();
using (var scope = provider.CreateScope())
{
var scoped1 = scope.ServiceProvider.GetRequiredService<IScopedService>();
var scoped2 = scope.ServiceProvider.GetRequiredService<IScopedService>();
Console.WriteLine($"Transient1与Transient2是否同一实例:{ReferenceEquals(transient1, transient2)}");
Console.WriteLine($"Scoped1与Scoped2是否同一实例:{ReferenceEquals(scoped1, scoped2)}");
}
var singleton1 = provider.GetRequiredService<ISingletonService>();
var singleton2 = provider.GetRequiredService<ISingletonService>();
Console.WriteLine($"Singleton1与Singleton2是否同一实例:{ReferenceEquals(singleton1, singleton2)}");
public interface ITransientService
{
}
public interface IScopedService
{
}
public interface ISingletonService
{
}
public class TransientService : ITransientService
{
}
public class ScopedService : IScopedService
{
}
public class SingletonService : ISingletonService
{
}
从示例可以看出,生命周期并不是写在服务类内部,而是由注册时选择的方法决定。同一个实现类理论上可以注册成不同生命周期,但实际项目中通常应该根据职责选择一种固定策略。若服务需要访问请求上下文,就适合 Scoped;若服务只处理一次输入输出,就适合 Transient;若服务需要全局共享,就适合 Singleton。
通过控制器观察三种生命周期的实际表现
为了更直观地验证差异,可以让三种服务在构造函数中打印实例哈希码。哈希码用于区分不同对象实例,并不用于生产环境中的身份标识。控制器中同时注入同一个接口的两个参数,可以观察容器在单次解析过程中是否返回相同实例。
示例定义了三组接口与实现,并在控制器中分别注入两次。每次 HTTP GET 请求都会触发一次控制器实例化,因此可以观察 Transient 是否每次都新建,Scoped 是否在同一请求内复用,Singleton 是否跨请求复用。
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddTransient<ITransientService, TransientService>();
builder.Services.AddScoped<IScopedService, ScopedService>();
builder.Services.AddSingleton<ISingletonService, SingletonService>();
var app = builder.Build();
app.MapControllers();
app.Run();
public interface ITransientService
{
}
public interface IScopedService
{
}
public interface ISingletonService
{
}
public class TransientService : ITransientService
{
public TransientService()
{
Console.WriteLine($"Transient实例创建,哈希码:{this.GetHashCode()}");
}
}
public class ScopedService : IScopedService
{
public ScopedService()
{
Console.WriteLine($"Scoped实例创建,哈希码:{this.GetHashCode()}");
}
}
public class SingletonService : ISingletonService
{
public SingletonService()
{
Console.WriteLine($"Singleton实例创建,哈希码:{this.GetHashCode()}");
}
}
[ApiController]
[Route("api/[controller]")]
public class TestController : ControllerBase
{
private readonly ITransientService _transient1;
private readonly ITransientService _transient2;
private readonly IScopedService _scoped1;
private readonly IScopedService _scoped2;
private readonly ISingletonService _singleton1;
private readonly ISingletonService _singleton2;
public TestController(
ITransientService transient1,
ITransientService transient2,
IScopedService scoped1,
IScopedService scoped2,
ISingletonService singleton1,
ISingletonService singleton2)
{
_transient1 = transient1;
_transient2 = transient2;
_scoped1 = scoped1;
_scoped2 = scoped2;
_singleton1 = singleton1;
_singleton2 = singleton2;
}
[HttpGet]
public IActionResult Get()
{
Console.WriteLine($"Transient1哈希:{_transient1.GetHashCode()},Transient2哈希:{_transient2.GetHashCode()}");
Console.WriteLine($"Scoped1哈希:{_scoped1.GetHashCode()},Scoped2哈希:{_scoped2.GetHashCode()}");
Console.WriteLine($"Singleton1哈希:{_singleton1.GetHashCode()},Singleton2哈希:{_singleton2.GetHashCode()}");
return Ok();
}
}
第一次请求时,控制台通常会看到 Transient 创建两个不同实例,Scoped 创建一个实例,Singleton 创建一个实例。控制器内部打印的哈希码会显示:两个 Transient 参数不同,两个 Scoped 参数相同,两个 Singleton 参数相同。
Transient实例创建,哈希码:12345
Transient实例创建,哈希码:23456
Scoped实例创建,哈希码:34567
Singleton实例创建,哈希码:45678
Transient1哈希:12345,Transient2哈希:23456
Scoped1哈希:34567,Scoped2哈希:34567
Singleton1哈希:45678,Singleton2哈希:45678
第二次请求时,Transient 会再次创建两个新实例,Scoped 也会为新的请求作用域创建新实例,而 Singleton 不会再次创建,仍然返回第一次请求中已经创建的那个实例。
Transient实例创建,哈希码:56789
Transient实例创建,哈希码:67890
Scoped实例创建,哈希码:78901
Transient1哈希:56789,Transient2哈希:67890
Scoped1哈希:78901,Scoped2哈希:78901
Singleton1哈希:45678,Singleton2哈希:45678
这个结果说明,生命周期不是由注入次数决定的,而是由容器维护的实例缓存边界决定的。Transient 没有跨解析缓存,Scoped 有请求级缓存,Singleton 有应用级缓存。
选择生命周期的工程原则
选择生命周期时,首先要判断服务是否持有状态。无状态服务通常可以使用 Transient,因为每次创建新实例不会丢失必要信息,也不容易引入并发问题。有状态服务则需要进一步判断状态属于哪一层:如果状态只属于当前请求,例如数据库上下文、用户会话、临时工作单元,应使用 Scoped;如果状态属于整个应用,例如配置、缓存、客户端连接,应使用 Singleton。
其次要考虑创建成本。如果服务构造函数需要读取配置、建立连接、初始化复杂对象,频繁创建会带来性能压力,此时应优先考虑 Scoped 或 Singleton。若服务只是轻量工具类,使用 Transient 更简单安全。第三要考虑并发访问。Singleton 可能被多个线程同时使用,若内部有可变字段,必须使用锁、并发集合或不可变设计。Scoped 在单个请求内通常由同一请求线程使用,但仍可能通过异步操作、后台任务等跨越线程,不能盲目假设绝对安全。
在实际项目中,可以把生命周期选择归纳为三类判断:第一,服务是否需要在多次调用之间保持数据;第二,这些数据的有效期是单次请求还是整个应用;第三,服务创建和销毁的成本是否值得通过共享来摊薄。满足前两个问题后,再结合并发模型做最终决定,通常就能避免大多数生命周期误用。
- Transient:适合无状态的服务,比如数据校验工具、简单的计算服务、一次性格式化器等,不需要维护状态,每次使用新实例也不会有额外负担。
- Scoped:适合需要绑定请求上下文的服务,比如数据库上下文、请求级别的缓存服务、工作单元等,避免同一个请求内多次创建相同资源。
- Singleton:适合全局共享的服务,比如配置读取服务、日志服务、全局缓存、外部客户端等,或者创建成本很高的服务,避免重复创建浪费资源。
避免错误组合与手动创建作用域
依赖注入中最常见的错误之一,是把短生命周期服务注入到长生命周期服务中。例如把 Scoped 服务注入 Singleton 服务,Singleton 会在第一次解析时捕获某个 Scoped 实例,并长期持有它。这个 Scoped 实例不会随着原始请求结束而释放,可能导致内存泄漏、数据库连接被长期占用,或者在不同请求之间看到错误的状态。
如果 Singleton 确实需要使用 Scoped 服务,正确做法是通过 IServiceScopeFactory 手动创建作用域。每次需要访问 Scoped 服务时,都新建一个作用域,使用完毕后释放。这样 Scoped 服务的生命周期仍然受控,不会错误地绑定到 Singleton 上。示例展示了这种处理方式。
using System;
using Microsoft.Extensions.DependencyInjection;
public interface IScopedService
{
}
public class ScopedService : IScopedService
{
public ScopedService()
{
Console.WriteLine($"Scoped实例创建,哈希码:{this.GetHashCode()}");
}
}
public interface ISingletonService
{
void DoWork();
}
public class SingletonService : ISingletonService
{
private readonly IServiceScopeFactory _scopeFactory;
public SingletonService(IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
}
public void DoWork()
{
// 每次需要访问 Scoped 服务时,创建独立作用域
using (var scope = _scopeFactory.CreateScope())
{
var scopedService = scope.ServiceProvider.GetRequiredService<IScopedService>();
Console.WriteLine($"在Singleton中获取Scoped实例,哈希码:{scopedService.GetHashCode()}");
}
}
}
在实际项目中,建议把“被依赖服务的生命周期应长于或等于当前服务”作为检查规则。审查代码时,如果发现 Singleton 构造函数中接收了 Scoped 或 Transient 依赖,应优先重新设计服务边界。必要时可以把需要请求上下文的部分拆成 Scoped 服务,由请求层直接调用,而不是让 Singleton 持有它。
总结来看,Transient、Scoped 和 Singleton 并不是优劣之分,而是不同共享边界的表达。Transient 强调每次解析独立,Scoped 强调请求内共享,Singleton 强调应用级共享。配置生命周期时,应同时考虑状态、创建成本、并发安全和释放时机。掌握这些原则后,依赖注入才能真正成为管理对象复杂度的工具,而不是隐藏资源问题的地方。