C#在 .NET中使用依赖注入的示例详解
作者:rjcql
这篇文章主要为大家详细介绍了C#如何在 .NET中使用依赖注入,文中的示例代码讲解详细,具有一定的学习价值,感兴趣的小伙伴可以跟随小编一起了解一下
写在前面
在 .NET 中使用依赖注入 (DI)。 可以借助 Microsoft 扩展,通过添加服务并在 IServiceCollection 中配置这些服务来管理 DI。 使用 IHost 接口来公开所有 IServiceProvider 实例,用来充当所有已注册的服务的容器。
示例代码中使用了一个关键的枚举 ServiceLifetime 指定 IServiceCollection 中服务的生存期,该枚举包含三个类型:
Scoped 服务只会随着新范围而改变,但在一个范围中是相同的实例。
Singleton 服务总是相同的,新实例仅被创建一次。
Transient 服务总是不同的,每次检索服务时,都会创建一个新实例。
需要从NuGet安装 Microsoft.Extensions.Hosting 类库

代码实现
服务接口实现
using Microsoft.Extensions.DependencyInjection;
namespace ConsoleDI.Example;
public interface IReportServiceLifetime
{
Guid Id { get; }
ServiceLifetime Lifetime { get; }
}
// 创建了多个接口和相应的实现。 其中每个服务都唯一标识并与 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, "在函数域范围内只创建一次,不同函数内为不同对象");
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#依赖注入内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
