没有找到合适的类型构造函数

Tau*_*qir 2 c# dependency-injection

我正在尝试最简单的IHttpClientFactory用例

public interface IWeatherForecast
{
    Task<string> Get();
}

class WeatherForecast : IWeatherForecast
{
    private readonly HttpClient httpClient;
    public WeatherForecast (IHttpClientFactory httpClientFactory)
    {
        httpClient = httpClientFactory.CreateClient();
    }
    public async Task<string> Get()
    {
        var resp = await httpClient.GetAsync("https://testwebapiforuseinsamples.azurewebsites.net/weatherforecast");
        return JsonConvert.SerializeObject(resp.Content.ReadAsStringAsync());
    }
}
Run Code Online (Sandbox Code Playgroud)

然后实例化它

static async Task Main(string[] args)
{
    var container = new ServiceCollection();
    container.AddHttpClient<IWeatherForecast, WeatherForecast>();
    var serviceProvider = container.BuildServiceProvider();    
    var resp = await serviceProvider.GetRequiredService<WeatherForecast>().Get();
}
Run Code Online (Sandbox Code Playgroud)

但是当我运行它时,它会抛出

System.InvalidOperationException:“无法找到类型“HttpClientFactoryExample.WeatherForecast”的合适构造函数。确保类型是具体的...

有人能指出这段代码有什么问题吗?我期望在将WeatherForecast服务添加到 DI 后,我将能够从容器中获取它的初始化实例。

Яро*_*вич 7

当您将 Service 集合中的类型注册为 HTTP client 时container.AddHttpClient<IWeatherForecast, WeatherForecast>(),它必须包含HttpClient在构造函数中。在你的情况下应该是:

public WeatherForecast(HttpClient httpClient)
{
     this.httpClient = httpClient;
}
Run Code Online (Sandbox Code Playgroud)

另一种选择是单独注册HttpClientFactory您的WeatherForecast服务:

container.AddHttpClient();
container.AddTransient<IWeatherForecast, WeatherForecast>();
Run Code Online (Sandbox Code Playgroud)

然后将服务与 HttpClientFactory 一起使用:

private readonly HttpClient httpClient;

public WeatherForecast(IHttpClientFactory factory)
{
    this.httpClient = factory.CreateClient();
}
Run Code Online (Sandbox Code Playgroud)