C#在 .NET中使用依賴注入的示例詳解
寫在前面
在 .NET 中使用依賴注入 (DI)。 可以借助 Microsoft 擴展,通過添加服務并在 IServiceCollection 中配置這些服務來管理 DI。 使用 IHost 接口來公開所有 IServiceProvider 實例,用來充當所有已注冊的服務的容器。
示例代碼中使用了一個關鍵的枚舉 ServiceLifetime 指定 IServiceCollection 中服務的生存期,該枚舉包含三個類型:
Scoped 服務只會隨著新范圍而改變,但在一個范圍中是相同的實例。
Singleton 服務總是相同的,新實例僅被創(chuàng)建一次。
Transient 服務總是不同的,每次檢索服務時,都會創(chuàng)建一個新實例。
需要從NuGet安裝 Microsoft.Extensions.Hosting 類庫

代碼實現(xiàn)
服務接口實現(xiàn)
using Microsoft.Extensions.DependencyInjection;
namespace ConsoleDI.Example;
public interface IReportServiceLifetime
{
Guid Id { get; }
ServiceLifetime Lifetime { get; }
}
// 創(chuàng)建了多個接口和相應的實現(xiàn)。 其中每個服務都唯一標識并與 ServiceLifetime 配對
public interface IExampleTransientService : IReportServiceLifetime
{
ServiceLifetime IReportServiceLifetime.Lifetime => ServiceLifetime.Transient;
}
public interface IExampleScopedService : IReportServiceLifetime
{
ServiceLifetime IReportServiceLifetime.Lifetime => ServiceLifetime.Scoped;
}
public interface IExampleSingletonService : IReportServiceLifetime
{
ServiceLifetime IReportServiceLifetime.Lifetime => ServiceLifetime.Singleton;
}
internal sealed class ExampleTransientService : IExampleTransientService
{
Guid IReportServiceLifetime.Id { get; } = Guid.NewGuid();
}
internal sealed class ExampleScopedService : IExampleScopedService
{
Guid IReportServiceLifetime.Id { get; } = Guid.NewGuid();
}
internal sealed class ExampleSingletonService : IExampleSingletonService
{
Guid IReportServiceLifetime.Id { get; } = Guid.NewGuid();
}
示例代碼
namespace ConsoleDI.Example;
internal sealed class ServiceLifetimeReporter(
IExampleTransientService transientService,
IExampleScopedService scopedService,
IExampleSingletonService singletonService)
{
public void ReportServiceLifetimeDetails(string lifetimeDetails)
{
Console.WriteLine(lifetimeDetails);
LogService(transientService, "每次都是新建的對象,一直保持不同");
LogService(scopedService, "在函數(shù)域范圍內只創(chuàng)建一次,不同函數(shù)內為不同對象");
LogService(singletonService, "全局單例,一直是同一個");
}
private static void LogService<T>(T service, string message)
where T : IReportServiceLifetime =>
Console.WriteLine($" {typeof(T).Name}: {service.Id} ({message})");
}
調用示例

到此這篇關于C#在 .NET中使用依賴注入的示例詳解的文章就介紹到這了,更多相關C#依賴注入內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C#實現(xiàn)改變DataGrid某一行和單元格顏色的方法
這篇文章主要介紹了C#實現(xiàn)改變DataGrid某一行和單元格顏色的方法,主要涉及DataGrid控件的添加與使用、數(shù)據(jù)源的綁定、單元格與行的獲取等操作。需要的朋友可以參考下2014-09-09
解析C#中的私有構造函數(shù)和靜態(tài)構造函數(shù)
這篇文章主要介紹了C#中的私有構造函數(shù)和靜態(tài)構造函數(shù),是C#入門學習中的基礎知識,需要的朋友可以參考下2016-01-01
c#求范圍內素數(shù)的示例分享(c#求素數(shù))
問題是判斷101-200之間有多少個素數(shù),并輸出所有素數(shù)。下面是使用C#解決這個問題的方法 ,需要的朋友可以參考下2014-03-03

