【微软技术栈】C#.NET 中使用依赖注入

这篇具有很好参考价值的文章主要介绍了【微软技术栈】C#.NET 中使用依赖注入。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

本文内容

  1. 先决条件
  2. 创建新的控制台应用程序
  3. 添加接口
  4. 添加默认实现
  5. 添加需要 DI 的服务
  6. 为 DI 注册服务
  7. 结束语

本文介绍如何在 .NET 中使用依赖注入 (DI)。 借助 Microsoft 扩展,可通过添加服务并在 IServiceCollection 中配置这些服务来管理 DI。 IHost 接口会公开 IServiceProvider 实例,它充当所有已注册的服务的容器。

本文介绍如何执行下列操作:

  • 创建一个使用依赖注入的 .NET 控制台应用
  • 生成和配置通用主机
  • 编写多个接口及相应的实现
  • 为 DI 使用服务生存期和范围设定

1、先决条件

  • .NET Core 3.1 SDK 或更高版本。
  • 熟悉如何创建新的 .NET 应用程序以及如何安装 NuGet 包。

2、创建新的控制台应用程序

通过 dotnet new 命令或 IDE 的“新建项目”向导,新建一个名为 ConsoleDI 的 .NET 控制台应用程序 Example 。 将 NuGet 包 Microsoft.Extensions.Hosting 添加到项目。

新的控制台应用项目文件应如下所示:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>true</ImplicitUsings>
    <RootNamespace>ConsoleDI.Example</RootNamespace>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" />
  </ItemGroup>

</Project>

 重要

在此示例中,需要 NuGet 包 Microsoft.Extensions.Hosting 来生成和运行应用。 某些元包可能包含 Microsoft.Extensions.Hosting 包,在这种情况下,不需要显式包引用。

3、添加接口

在此示例应用中,你将了解依赖项注入如何处理服务生存期。 你将创建多个表示不同服务生存期的接口。 将以下接口添加到项目根目录:

IReportServiceLifetime.cs

using Microsoft.Extensions.DependencyInjection;

namespace ConsoleDI.Example;

public interface IReportServiceLifetime
{
    Guid Id { get; }

    ServiceLifetime Lifetime { get; }
}

IReportServiceLifetime 接口定义了以下项:

  • 表示服务的唯一标识符的 Guid Id 属性。
  • 表示服务生存期的 ServiceLifetime 属性。

IExampleTransientService.cs

using Microsoft.Extensions.DependencyInjection;

namespace ConsoleDI.Example;

public interface IExampleTransientService : IReportServiceLifetime
{
    ServiceLifetime IReportServiceLifetime.Lifetime => ServiceLifetime.Transient;
}

IExampleScopedService.cs

using Microsoft.Extensions.DependencyInjection;

namespace ConsoleDI.Example;

public interface IExampleScopedService : IReportServiceLifetime
{
    ServiceLifetime IReportServiceLifetime.Lifetime => ServiceLifetime.Scoped;
}

IExampleSingletonService.cs

using Microsoft.Extensions.DependencyInjection;

namespace ConsoleDI.Example;

public interface IExampleSingletonService : IReportServiceLifetime
{
    ServiceLifetime IReportServiceLifetime.Lifetime => ServiceLifetime.Singleton;
}

IReportServiceLifetime 的所有子接口均使用默认值显式实现 IReportServiceLifetime.Lifetime。 例如,IExampleTransientService 使用 ServiceLifetime.Transient 值显式实现 IReportServiceLifetime.Lifetime

4、添加默认实现

该示例实现使用 Guid.NewGuid() 的结果初始化其 Id 属性。 将各种服务的下列默认实现类添加到项目根目录:

ExampleTransientService.cs

namespace ConsoleDI.Example;

internal sealed class ExampleTransientService : IExampleTransientService
{
    Guid IReportServiceLifetime.Id { get; } = Guid.NewGuid();
}

ExampleScopedService.cs

namespace ConsoleDI.Example;

internal sealed class ExampleScopedService : IExampleScopedService
{
    Guid IReportServiceLifetime.Id { get; } = Guid.NewGuid();
}

ExampleSingletonService.cs

namespace ConsoleDI.Example;

internal sealed class ExampleSingletonService : IExampleSingletonService
{
    Guid IReportServiceLifetime.Id { get; } = Guid.NewGuid();
}

每个实现都定义为 internal sealed 并实现其相应的接口。 例如,ExampleSingletonService 会实现 IExampleSingletonService

5、添加需要 DI 的服务

添加下列服务生存期报告器类,它作为服务添加到控制台应用:

ServiceLifetimeReporter.cs

namespace ConsoleDI.Example;

internal sealed class ServiceLifetimeReporter
{
    private readonly IExampleTransientService _transientService;
    private readonly IExampleScopedService _scopedService;
    private readonly IExampleSingletonService _singletonService;

    public ServiceLifetimeReporter(
        IExampleTransientService transientService,
        IExampleScopedService scopedService,
        IExampleSingletonService singletonService) =>
        (_transientService, _scopedService, _singletonService) =
            (transientService, scopedService, singletonService);

    public void ReportServiceLifetimeDetails(string lifetimeDetails)
    {
        Console.WriteLine(lifetimeDetails);

        LogService(_transientService, "Always different");
        LogService(_scopedService, "Changes only with lifetime");
        LogService(_singletonService, "Always the same");
    }

    private static void LogService<T>(T service, string message)
        where T : IReportServiceLifetime =>
        Console.WriteLine(
            $"    {typeof(T).Name}: {service.Id} ({message})");
}

ServiceLifetimeReporter 会定义一个构造函数,该函数需要上述每一个服务接口(即 IExampleTransientServiceIExampleScopedService 和 IExampleSingletonService)。 对象会公开一个方法,使用者可通过该方法使用给定的 lifetimeDetails 参数报告服务。 被调用时,ReportServiceLifetimeDetails 方法会使用服务生存期消息记录每个服务的唯一标识符。 日志消息有助于直观呈现服务生存期。

6、为 DI 注册服务

使用以下代码更新 Program.cs:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ConsoleDI.Example;

HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);

builder.Services.AddTransient<IExampleTransientService, ExampleTransientService>();
builder.Services.AddScoped<IExampleScopedService, ExampleScopedService>();
builder.Services.AddSingleton<IExampleSingletonService, ExampleSingletonService>();
builder.Services.AddTransient<ServiceLifetimeReporter>();

using IHost host = builder.Build();

ExemplifyServiceLifetime(host.Services, "Lifetime 1");
ExemplifyServiceLifetime(host.Services, "Lifetime 2");

await host.RunAsync();

static void ExemplifyServiceLifetime(IServiceProvider hostProvider, string lifetime)
{
    using IServiceScope serviceScope = hostProvider.CreateScope();
    IServiceProvider provider = serviceScope.ServiceProvider;
    ServiceLifetimeReporter logger = provider.GetRequiredService<ServiceLifetimeReporter>();
    logger.ReportServiceLifetimeDetails(
        $"{lifetime}: Call 1 to provider.GetRequiredService<ServiceLifetimeReporter>()");

    Console.WriteLine("...");

    logger = provider.GetRequiredService<ServiceLifetimeReporter>();
    logger.ReportServiceLifetimeDetails(
        $"{lifetime}: Call 2 to provider.GetRequiredService<ServiceLifetimeReporter>()");

    Console.WriteLine();
}

每个 services.Add{LIFETIME}<{SERVICE}> 扩展方法添加(并可能配置)服务。 我们建议应用遵循此约定。 将扩展方法置于 Microsoft.Extensions.DependencyInjection 命名空间中以封装服务注册的组。 还包括用于 DI 扩展方法的命名空间部分 Microsoft.Extensions.DependencyInjection

  • 允许在不添加其他 using 块的情况下在 IntelliSense 中显示它们。
  • 在通常会调用这些扩展方法的 Program 或 Startup 类中,避免出现过多的 using 语句。

应用会执行以下操作:

  • 使用默认活页夹设置创建一个 IHostBuilder 实例。
  • 配置服务并对其添加相应的服务生存期。
  • 调用 Build() 并分配 IHost 的实例。
  • 调用 ExemplifyScoping,传入 IHost.Services。

7、结束语

在此示例应用中,你创建了多个接口和相应的实现。 其中每个服务都唯一标识并与 ServiceLifetime 配对。 示例应用演示了如何针对接口注册服务实现,以及如何在没有支持接口的情况下注册纯类。 然后,示例应用演示了如何在运行时解析定义为构造函数参数的依赖项。

运行该应用时,它会显示如下所示的输出:

// Sample output:
// Lifetime 1: Call 1 to provider.GetRequiredService<ServiceLifetimeReporter>()
//     IExampleTransientService: d08a27fa-87d2-4a06-98d7-2773af886125 (Always different)
//     IExampleScopedService: 402c83c9-b4ed-4be1-b78c-86be1b1d908d (Changes only with lifetime)
//     IExampleSingletonService: a61f1ff4-0b14-4508-bd41-21d852484a7b (Always the same)
// ...
// Lifetime 1: Call 2 to provider.GetRequiredService<ServiceLifetimeReporter>()
//     IExampleTransientService: b43d68fb-2c7b-4a9b-8f02-fc507c164326 (Always different)
//     IExampleScopedService: 402c83c9-b4ed-4be1-b78c-86be1b1d908d (Changes only with lifetime)
//     IExampleSingletonService: a61f1ff4-0b14-4508-bd41-21d852484a7b (Always the same)
// 
// Lifetime 2: Call 1 to provider.GetRequiredService<ServiceLifetimeReporter>()
//     IExampleTransientService: f3856b59-ab3f-4bbd-876f-7bab0013d392 (Always different)
//     IExampleScopedService: bba80089-1157-4041-936d-e96d81dd9d1c (Changes only with lifetime)
//     IExampleSingletonService: a61f1ff4-0b14-4508-bd41-21d852484a7b (Always the same)
// ...
// Lifetime 2: Call 2 to provider.GetRequiredService<ServiceLifetimeReporter>()
//     IExampleTransientService: a8015c6a-08cd-4799-9ec3-2f2af9cbbfd2 (Always different)
//     IExampleScopedService: bba80089-1157-4041-936d-e96d81dd9d1c (Changes only with lifetime)
//     IExampleSingletonService: a61f1ff4-0b14-4508-bd41-21d852484a7b (Always the same)

在应用输出中,可看到:文章来源地址https://www.toymoban.com/news/detail-758232.html

  • Transient 服务总是不同的,每次检索服务时,都会创建一个新实例。
  • Scoped 服务只会随着新范围而改变,但在一个范围中是相同的实例。
  • Singleton 服务总是相同的,新实例仅被创建一次。

到了这里,关于【微软技术栈】C#.NET 中使用依赖注入的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • net6 winform使用依赖注入(IOC)

    依赖注入(DI)是一种设计模式,它可以消除编程代码之间的依赖性,因此可以很容易地管理和测试应用程序。它有三种类型分别为构造函数注入,属性注入以及方法注入。它具有减少依赖性增强组件的可重用性等好处。 通俗的来说我们不通过 new 的方式在类内部创建依赖类

    2024年02月05日
    浏览(32)
  • .NET Core 依赖注入

    在.NET Core中,依赖注入(Dependency Injection,简称DI)是框架的一个重要特性,可以帮助我们解耦代码、管理对象生命周期以及提高可测试性等.一下是.NET Core中依赖注入的一些基本概念和用法: 1、服务(Service):在DI中,服务即一个对象或者类型。用于完成特定的功能.例如,数据库访

    2023年04月24日
    浏览(26)
  • .Net依赖注入神器Scrutor(上)

    从.Net Core 开始,.Net 平台内置了一个轻量,易用的 IOC 的框架,供我们在应用程序中使用,社区内还有很多强大的第三方的依赖注入框架如: Autofac DryIOC Grace LightInject Lamar Stashbox Simple Injector 内置的依赖注入容器基本可以满足大多数应用的需求,除非你需要的特定功能不受它支

    2024年03月19日
    浏览(32)
  • .NET 通过源码深究依赖注入原理

    依赖注入 (DI) 是.NET中一个非常重要的软件设计模式,它可以帮助我们更好地管理和组织组件,提高代码的可读性,扩展性和可测试性。在日常工作中,我们一定遇见过这些问题或者疑惑。 Singleton服务为什么不能依赖Scoped服务? 多个构造函数的选择机制? 源码是如何识别循环

    2024年02月05日
    浏览(52)
  • 【ASP.NET Core 基础知识】--依赖注入(DI)--什么是依赖注入

    依赖注入(Dependency Injection,简称DI)是一种设计模式,用于解耦和管理类之间的依赖关系。它的核心思想是将原本需要在代码中显式创建的依赖关系,交给外部容器进行控制和管理。 具体来说,依赖注入的实现方式是通过将依赖对象的创建和维护责任转移到外部容器中,使

    2024年01月23日
    浏览(44)
  • 【.NET6+WPF】WPF使用prism框架+Unity IOC容器实现MVVM双向绑定和依赖注入

    前言:在C/S架构上,WPF无疑已经是“桌面一霸”了。在.NET生态环境中,很多小伙伴还在使用Winform开发C/S架构的桌面应用。但是WPF也有很多年的历史了,并且基于MVVM的开发模式,受到了很多开发者的喜爱。 并且随着工业化的进展,以及几年前微软对.NET平台的开源,国内大多

    2024年02月06日
    浏览(45)
  • .NET 6 整合 Autofac 依赖注入容器

    一行业务代码还没写,框架代码一大堆,不利于学习。 常看到java的学习资料或博客,标题一般为《SpringBoot 整合 XXX》,所以仿照着写了《.NET 6 整合 Autofac 依赖注入容器》这样一个标题。 以下是我自己的用法,可能不是最佳实践。 NuGet搜索并安装: Autofac Autofac.Extensions.Depe

    2023年04月26日
    浏览(31)
  • .Net6.0系列-7 依赖注入(一)

    依赖注入(Dependency Injection,DI)是控制反转(Inversion of Control,IOC)思想的实现方式,依赖注入简化模块的组装过程,降低模块之间的耦合度. DI的几个概念: 服务(Service):和框架请求之后返回的一个对象,可以是一个数据库链接,也可以是一个文件处理的方法,或者是数据处理的一个过程方法

    2023年04月11日
    浏览(33)
  • ASP.NET WebApi 极简依赖注入

    .NET Core 7.0 ASP.NET Core Visual Studio 2022 .Net Core WebApi Redis消息订阅 ASP.NET Core 依赖注入最佳实践 简单来说就是 有效地设计服务及其依赖关系。 防止多线程问题。 防止内存泄漏。 防止潜在的错误。

    2024年02月08日
    浏览(28)
  • 【C#/.NET】MAUI上的依赖注入

    ​         在移动应用开发中,依赖注入是一项非常重要的技术,它可以帮助我们简化代码结构、提高可维护性并增加测试覆盖率。在最新的.NET跨平台框架MAUI中,我们也可以利用依赖注入来构建高效的应用程序架构。本文将详细介绍在MAUI上如何使用依赖注入,旨在帮助

    2024年02月11日
    浏览(26)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包