在C#的.NET应用开发中,依赖注入(DI)是管理服务依赖的核心机制,而生命周期配置决定了服务实例的创建、复用和销毁时机。.NET内置的依赖注入容器支持三种标准生命周期:Transient、Scoped、Singleton,理解它们的差异是正确使用依赖注入的基础。

三种生命周期的核心定义
Transient(瞬态)
每次从依赖注入容器请求该服务时,都会创建一个新的实例。无论请求来自同一个作用域还是不同作用域,只要发起请求就会生成新对象,适合无状态、轻量级的短期服务。
Scoped(作用域)
在同一个作用域内,多次请求该服务会返回同一个实例;不同作用域之间会创建新的实例。在Web应用中,一个HTTP请求通常对应一个作用域,因此Scoped服务在同一个请求内是单例的。
Singleton(单例)
整个应用程序生命周期内,只会创建一个服务实例,后续所有请求都返回这个唯一的实例。适合需要全局共享状态、或者创建成本较高的服务。
生命周期配置方法
在.NET应用中,我们通常在Program.cs的IServiceCollection中配置服务的生命周期,以下是三种模式的配置示例:
// 配置Transient生命周期服务 builder.Services.AddTransient<ITransientService, TransientService>(); // 配置Scoped生命周期服务 builder.Services.AddScoped<IScopedService, ScopedService>(); // 配置Singleton生命周期服务 builder.Services.AddSingleton<ISingletonService, SingletonService>();
实例验证差异
我们可以定义三个不同生命周期的服务接口和实现,通过打印实例的哈希码来验证实例的创建规则:
// 服务接口定义
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实例创建,哈希码:12345
Transient实例创建,哈希码:23456
Scoped实例创建,哈希码:34567
Singleton实例创建,哈希码:45678
Transient1哈希:12345,Transient2哈希:23456
Scoped1哈希:34567,Scoped2哈希:34567
Singleton1哈希:45678,Singleton2哈希:45678
第二次请求接口时,输出结果类似:
Transient实例创建,哈希码:56789
Transient实例创建,哈希码:67890
Scoped实例创建,哈希码:78901
Transient1哈希:56789,Transient2哈希:67890
Scoped1哈希:78901,Scoped2哈希:78901
Singleton1哈希:45678,Singleton2哈希:45678
从结果可以明确看出:Transient每次注入都创建新实例,同一个作用域内Scoped注入的是同一个实例,Singleton无论何时注入都是同一个实例。
使用场景建议
- Transient:适合无状态的服务,比如数据校验工具、简单的计算服务等,不需要维护状态,每次使用新实例也不会有额外负担。
- Scoped:适合需要绑定请求上下文的服务,比如数据库上下文(Entity Framework Core的DbContext默认就是Scoped)、请求级别的缓存服务等,避免同一个请求内多次创建相同资源。
- Singleton:适合全局共享的服务,比如配置读取服务、日志服务、缓存服务(如果缓存是全局共享的),或者创建成本很高的服务,避免重复创建浪费资源。
注意事项
不能将生命周期短的服务注入到生命周期长的服务中,比如不能把Transient或Scoped服务注入到Singleton服务中,否则会导致短生命周期的服务被长生命周期的服务持有,无法及时释放,甚至引发状态异常。如果确实有这类需求,可以通过IServiceScopeFactory手动创建作用域来获取对应服务。
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>();
// 使用scopedService
}
}
}