国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

【微軟技術(shù)?!緾#.NET 中使用依賴注入

這篇具有很好參考價值的文章主要介紹了【微軟技術(shù)棧】C#.NET 中使用依賴注入。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

本文內(nèi)容

  1. 先決條件
  2. 創(chuàng)建新的控制臺應(yīng)用程序
  3. 添加接口
  4. 添加默認(rèn)實現(xiàn)
  5. 添加需要 DI 的服務(wù)
  6. 為 DI 注冊服務(wù)
  7. 結(jié)束語

本文介紹如何在 .NET 中使用依賴注入 (DI)。 借助 Microsoft 擴展,可通過添加服務(wù)并在?IServiceCollection?中配置這些服務(wù)來管理 DI。?IHost?接口會公開?IServiceProvider?實例,它充當(dāng)所有已注冊的服務(wù)的容器。

本文介紹如何執(zhí)行下列操作:

  • 創(chuàng)建一個使用依賴注入的 .NET 控制臺應(yīng)用
  • 生成和配置通用主機
  • 編寫多個接口及相應(yīng)的實現(xiàn)
  • 為 DI 使用服務(wù)生存期和范圍設(shè)定

1、先決條件

  • .NET Core 3.1 SDK?或更高版本。
  • 熟悉如何創(chuàng)建新的 .NET 應(yīng)用程序以及如何安裝 NuGet 包。

2、創(chuàng)建新的控制臺應(yīng)用程序

通過?dotnet new?命令或 IDE 的“新建項目”向?qū)В陆ㄒ粋€名為 ConsoleDI 的 .NET 控制臺應(yīng)用程序?Example?。 將 NuGet 包?Microsoft.Extensions.Hosting?添加到項目。

新的控制臺應(yīng)用項目文件應(yīng)如下所示:

<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?來生成和運行應(yīng)用。 某些元包可能包含?Microsoft.Extensions.Hosting?包,在這種情況下,不需要顯式包引用。

3、添加接口

在此示例應(yīng)用中,你將了解依賴項注入如何處理服務(wù)生存期。 你將創(chuàng)建多個表示不同服務(wù)生存期的接口。 將以下接口添加到項目根目錄:

IReportServiceLifetime.cs

using Microsoft.Extensions.DependencyInjection;

namespace ConsoleDI.Example;

public interface IReportServiceLifetime
{
    Guid Id { get; }

    ServiceLifetime Lifetime { get; }
}

IReportServiceLifetime?接口定義了以下項:

  • 表示服務(wù)的唯一標(biāo)識符的?Guid Id?屬性。
  • 表示服務(wù)生存期的?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?的所有子接口均使用默認(rèn)值顯式實現(xiàn)?IReportServiceLifetime.Lifetime。 例如,IExampleTransientService?使用?ServiceLifetime.Transient?值顯式實現(xiàn)?IReportServiceLifetime.Lifetime。

4、添加默認(rèn)實現(xiàn)

該示例實現(xiàn)使用?Guid.NewGuid()?的結(jié)果初始化其?Id?屬性。 將各種服務(wù)的下列默認(rèn)實現(xiàn)類添加到項目根目錄:

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();
}

每個實現(xiàn)都定義為?internal sealed?并實現(xiàn)其相應(yīng)的接口。 例如,ExampleSingletonService?會實現(xiàn)?IExampleSingletonService。

5、添加需要 DI 的服務(wù)

添加下列服務(wù)生存期報告器類,它作為服務(wù)添加到控制臺應(yīng)用:

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?會定義一個構(gòu)造函數(shù),該函數(shù)需要上述每一個服務(wù)接口(即?IExampleTransientService、IExampleScopedService?和?IExampleSingletonService)。 對象會公開一個方法,使用者可通過該方法使用給定的?lifetimeDetails?參數(shù)報告服務(wù)。 被調(diào)用時,ReportServiceLifetimeDetails?方法會使用服務(wù)生存期消息記錄每個服務(wù)的唯一標(biāo)識符。 日志消息有助于直觀呈現(xiàn)服務(wù)生存期。

6、為 DI 注冊服務(wù)

使用以下代碼更新 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}>?擴展方法添加(并可能配置)服務(wù)。 我們建議應(yīng)用遵循此約定。 將擴展方法置于?Microsoft.Extensions.DependencyInjection?命名空間中以封裝服務(wù)注冊的組。 還包括用于 DI 擴展方法的命名空間部分?Microsoft.Extensions.DependencyInjection

  • 允許在不添加其他?using?塊的情況下在?IntelliSense?中顯示它們。
  • 在通常會調(diào)用這些擴展方法的?Program?或?Startup?類中,避免出現(xiàn)過多的?using?語句。

應(yīng)用會執(zhí)行以下操作:

  • 使用默認(rèn)活頁夾設(shè)置創(chuàng)建一個?IHostBuilder?實例。
  • 配置服務(wù)并對其添加相應(yīng)的服務(wù)生存期。
  • 調(diào)用?Build()?并分配?IHost?的實例。
  • 調(diào)用?ExemplifyScoping,傳入?IHost.Services。

7、結(jié)束語

在此示例應(yīng)用中,你創(chuàng)建了多個接口和相應(yīng)的實現(xiàn)。 其中每個服務(wù)都唯一標(biāo)識并與?ServiceLifetime?配對。 示例應(yīng)用演示了如何針對接口注冊服務(wù)實現(xiàn),以及如何在沒有支持接口的情況下注冊純類。 然后,示例應(yīng)用演示了如何在運行時解析定義為構(gòu)造函數(shù)參數(shù)的依賴項。

運行該應(yīng)用時,它會顯示如下所示的輸出:

// 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)

在應(yīng)用輸出中,可看到:文章來源地址http://www.zghlxwxcb.cn/news/detail-758232.html

  • Transient 服務(wù)總是不同的,每次檢索服務(wù)時,都會創(chuàng)建一個新實例。
  • Scoped 服務(wù)只會隨著新范圍而改變,但在一個范圍中是相同的實例。
  • Singleton 服務(wù)總是相同的,新實例僅被創(chuàng)建一次。

到了這里,關(guān)于【微軟技術(shù)?!緾#.NET 中使用依賴注入的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

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

    net6 winform使用依賴注入(IOC)

    依賴注入(DI)是一種設(shè)計模式,它可以消除編程代碼之間的依賴性,因此可以很容易地管理和測試應(yīng)用程序。它有三種類型分別為構(gòu)造函數(shù)注入,屬性注入以及方法注入。它具有減少依賴性增強組件的可重用性等好處。 通俗的來說我們不通過 new 的方式在類內(nèi)部創(chuàng)建依賴類

    2024年02月05日
    瀏覽(19)
  • .NET Core 依賴注入

    在.NET Core中,依賴注入(Dependency Injection,簡稱DI)是框架的一個重要特性,可以幫助我們解耦代碼、管理對象生命周期以及提高可測試性等.一下是.NET Core中依賴注入的一些基本概念和用法: 1、服務(wù)(Service):在DI中,服務(wù)即一個對象或者類型。用于完成特定的功能.例如,數(shù)據(jù)庫訪

    2023年04月24日
    瀏覽(94)
  • .NET 通過源碼深究依賴注入原理

    .NET 通過源碼深究依賴注入原理

    依賴注入 (DI) 是.NET中一個非常重要的軟件設(shè)計模式,它可以幫助我們更好地管理和組織組件,提高代碼的可讀性,擴展性和可測試性。在日常工作中,我們一定遇見過這些問題或者疑惑。 Singleton服務(wù)為什么不能依賴Scoped服務(wù)? 多個構(gòu)造函數(shù)的選擇機制? 源碼是如何識別循環(huán)

    2024年02月05日
    瀏覽(30)
  • .Net依賴注入神器Scrutor(上)

    從.Net Core 開始,.Net 平臺內(nèi)置了一個輕量,易用的 IOC 的框架,供我們在應(yīng)用程序中使用,社區(qū)內(nèi)還有很多強大的第三方的依賴注入框架如: Autofac DryIOC Grace LightInject Lamar Stashbox Simple Injector 內(nèi)置的依賴注入容器基本可以滿足大多數(shù)應(yīng)用的需求,除非你需要的特定功能不受它支

    2024年03月19日
    瀏覽(42)
  • 【ASP.NET Core 基礎(chǔ)知識】--依賴注入(DI)--什么是依賴注入

    依賴注入(Dependency Injection,簡稱DI)是一種設(shè)計模式,用于解耦和管理類之間的依賴關(guān)系。它的核心思想是將原本需要在代碼中顯式創(chuàng)建的依賴關(guān)系,交給外部容器進(jìn)行控制和管理。 具體來說,依賴注入的實現(xiàn)方式是通過將依賴對象的創(chuàng)建和維護(hù)責(zé)任轉(zhuǎn)移到外部容器中,使

    2024年01月23日
    瀏覽(89)
  • 【.NET6+WPF】WPF使用prism框架+Unity IOC容器實現(xiàn)MVVM雙向綁定和依賴注入

    【.NET6+WPF】WPF使用prism框架+Unity IOC容器實現(xiàn)MVVM雙向綁定和依賴注入

    前言:在C/S架構(gòu)上,WPF無疑已經(jīng)是“桌面一霸”了。在.NET生態(tài)環(huán)境中,很多小伙伴還在使用Winform開發(fā)C/S架構(gòu)的桌面應(yīng)用。但是WPF也有很多年的歷史了,并且基于MVVM的開發(fā)模式,受到了很多開發(fā)者的喜愛。 并且隨著工業(yè)化的進(jìn)展,以及幾年前微軟對.NET平臺的開源,國內(nèi)大多

    2024年02月06日
    瀏覽(28)
  • .NET 6 整合 Autofac 依賴注入容器

    一行業(yè)務(wù)代碼還沒寫,框架代碼一大堆,不利于學(xué)習(xí)。 常看到j(luò)ava的學(xué)習(xí)資料或博客,標(biāo)題一般為《SpringBoot 整合 XXX》,所以仿照著寫了《.NET 6 整合 Autofac 依賴注入容器》這樣一個標(biāo)題。 以下是我自己的用法,可能不是最佳實踐。 NuGet搜索并安裝: Autofac Autofac.Extensions.Depe

    2023年04月26日
    瀏覽(28)
  • .Net6.0系列-7 依賴注入(一)

    依賴注入(Dependency Injection,DI)是控制反轉(zhuǎn)(Inversion of Control,IOC)思想的實現(xiàn)方式,依賴注入簡化模塊的組裝過程,降低模塊之間的耦合度. DI的幾個概念: 服務(wù)(Service):和框架請求之后返回的一個對象,可以是一個數(shù)據(jù)庫鏈接,也可以是一個文件處理的方法,或者是數(shù)據(jù)處理的一個過程方法

    2023年04月11日
    瀏覽(21)
  • ASP.NET Core 依賴注入系列一

    ASP.NET Core 依賴注入系列一

    什么是ASP.NET Core 依賴注入? 依賴注入也稱DI是一項技術(shù)用來實現(xiàn)對象松耦合以至于應(yīng)用程序更容易維護(hù),ASP.NET Core通過控制器的構(gòu)造函數(shù)自動注入依賴的對象,我們創(chuàng)建ASP.NET Core MVC應(yīng)用程序演示依賴注入特性是如何工作, 在這節(jié)中我們講解該特性 1 例子 我們創(chuàng)建一個ASP.NET C

    2024年02月11日
    瀏覽(98)
  • ASP.NET WebApi 極簡依賴注入

    ASP.NET WebApi 極簡依賴注入

    .NET Core 7.0 ASP.NET Core Visual Studio 2022 .Net Core WebApi Redis消息訂閱 ASP.NET Core 依賴注入最佳實踐 簡單來說就是 有效地設(shè)計服務(wù)及其依賴關(guān)系。 防止多線程問題。 防止內(nèi)存泄漏。 防止?jié)撛诘腻e誤。

    2024年02月08日
    瀏覽(94)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包