如何为构造函数包含HttpClient和一些字符串的类设置一些.NET Core Dependency Injection?

问题描述 投票:1回答:1

给定以下.NET Core 2.2类定义:

public class MyService : ISomeService
{
    public MyService(string apiKey, HttpClient httpClient) { ... } 
}

如何将DI设置为使用HttpClientFactory并在将ISomeService构造函数注入其他类时使用此具体实例?例如。

services.AddHttpClient<ISomeService, MyService>();
services.AddSingleton<ISomeService, MyService>(
    sp => new MyService("some api key from config", sp.GetService<??????????>() );
c# dependency-injection .net-core dotnet-httpclient
1个回答
2
投票

apiKey配置值提升为参数对象:

public sealed class MyServiceConfiguration
{
    public readonly string ApiKey;

    public MyServiceConfiguration(string apiKey)
    {
        if (string.IsNullOrEmpty(apiKey)) throw new ArgumentException(...);
        this.ApiKey = apiKey;
    }
}

并将您的MyService构造函数更改为:

public MyService(MyServiceConfiguration config, HttpClient httpClient)

新的MyServiceConfiguration可以很容易地注册如下:

services.AddSingleton(new MyServiceConfiguration("some api key from config"));

请注意使用HttpClient注入Singleton消费者。如hereherehere所述,当HttpClient实例在应用程序的持续时间内重复使用时会出现许多问题,这些问题将与您当前的配置一起使用。当您将MyService注册为Singleton时,HttpClient将成为Captive Dependency

相反,注册你的MyServiceScopedIdeally,ASP.NET Core应该能够为你检测这个Captive Dependency,但是在它当前的实现(v2.2)中它没有这样做,这意味着你最好通过制作你的直接消费者Scoped来保护自己(和清楚地记录为什么会这样,以防止下一个开发人员再次搞砸了事情。

© www.soinside.com 2019 - 2024. All rights reserved.