.NetCore依賴注入(DI)之生命周期
.NetCore依賴注入(DI)之生命周期
在 .NET Core 中,依賴注入(Dependency Injection,DI)是一種實(shí)現(xiàn)控制反轉(zhuǎn)(Inversion of Control,IoC)的技術(shù),它通過將依賴對(duì)象注入到需要它們的對(duì)象中,來實(shí)現(xiàn)對(duì)象之間的解耦。依賴注入的生命周期決定了對(duì)象在應(yīng)用程序中的創(chuàng)建和管理方式。常見的生命周期有三種:Transient(瞬態(tài))、Scoped(作用域) 和 Singleton(單例)。
1. Transient(瞬態(tài))
定義:
每次請(qǐng)求時(shí)都會(huì)創(chuàng)建一個(gè)新的實(shí)例。
特點(diǎn):
- 每次注入時(shí)都會(huì)創(chuàng)建一個(gè)新的對(duì)象。
- 對(duì)象的生命周期僅限于當(dāng)前請(qǐng)求。
- 適用于輕量級(jí)、無狀態(tài)的服務(wù)。
使用場景:
- 適用于每次請(qǐng)求都需要獨(dú)立實(shí)例的場景,例如工具類、無狀態(tài)服務(wù)等。
示例:
public interface ITransientService
{
Guid GetOperationId();
}
public class TransientService : ITransientService
{
private readonly Guid _operationId;
public TransientService()
{
_operationId = Guid.NewGuid();
}
public Guid GetOperationId() => _operationId;
}
在 Startup.cs 中注冊(cè):
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<ITransientService, TransientService>();
}
在控制器中使用:
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();
// 驗(yàn)證是否為不同實(shí)例
Console.WriteLine(_transientService1 == _transientService2); // 輸出:False
return Ok();
}
}
輸出:
Transient Service: Doing work...
Transient Service: Doing work...
False
2. Scoped(作用域)
定義:
在同一個(gè)作用域內(nèi),對(duì)象是單例的;但在不同的作用域中,會(huì)創(chuàng)建新的實(shí)例。
特點(diǎn):
- 對(duì)象的生命周期與請(qǐng)求的作用域一致。
- 適用于需要在請(qǐng)求范圍內(nèi)共享狀態(tài)的服務(wù)。
使用場景:
- 適用于需要在請(qǐng)求范圍內(nèi)共享狀態(tài)的場景,例如數(shù)據(jù)庫上下文、工作單元模式等。
示例:
public interface IScopedService
{
void DoWork();
}
public class ScopedService : IScopedService
{
public void DoWork()
{
Console.WriteLine("Scoped Service: Doing work...");
}
}
在 Startup.cs 中注冊(cè)
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IScopedService, ScopedService>();
}
在控制器中使用:
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();
// 驗(yàn)證是否為相同實(shí)例
Console.WriteLine(_scopedService1 == _scopedService2); // 輸出:True
return Ok();
}
}
輸出:
Scoped Service: Doing work...
Scoped Service: Doing work...
True
3. Singleton(單例)
定義:
在整個(gè)應(yīng)用程序生命周期中,只創(chuàng)建一個(gè)實(shí)例。
特點(diǎn):
- 對(duì)象的生命周期與應(yīng)用程序的生命周期一致。
- 適用于全局共享的服務(wù),如配置管理、日志記錄等。
使用場景:
- 適用于需要全局共享的場景,例如配置管理、緩存、日志記錄等。
示例:
public interface ISingletonService
{
void DoWork();
}
public class SingletonService : ISingletonService
{
public void DoWork()
{
Console.WriteLine("Singleton Service: Doing work...");
}
}
在 Startup.cs 中注冊(cè):
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ISingletonService, SingletonService>();
}
在控制器中使用:
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();
// 驗(yàn)證是否為相同實(shí)例
Console.WriteLine(_singletonService1 == _singletonService2); // 輸出:True
return Ok();
}
}
輸出:
Singleton Service: Doing work...
Singleton Service: Doing work...
True
總結(jié)
| 生命周期 | 定義 | 特點(diǎn) | 使用場景 |
|---|---|---|---|
| Transient | 每次請(qǐng)求時(shí)創(chuàng)建新的實(shí)例 | 每次注入時(shí)都會(huì)創(chuàng)建一個(gè)新的對(duì)象 | 輕量級(jí)、無狀態(tài)的服務(wù),如工具類、無狀態(tài)服務(wù) |
| Scoped | 在同一個(gè)作用域內(nèi),對(duì)象是單例的 | 對(duì)象的生命周期與請(qǐng)求的作用域一致 | 需要在請(qǐng)求范圍內(nèi)共享狀態(tài)的服務(wù),如數(shù)據(jù)庫上下文 |
| Singleton | 在整個(gè)應(yīng)用程序生命周期中,只創(chuàng)建一個(gè)實(shí)例 | 對(duì)象的生命周期與應(yīng)用程序的生命周期一致 | 全局共享的服務(wù),如配置管理、日志記錄 |
通過合理選擇依賴注入的生命周期,我們可以實(shí)現(xiàn)對(duì)象的靈活管理和高效使用,從而提高應(yīng)用程序的性能和可維護(hù)性。

浙公網(wǎng)安備 33010602011771號(hào)