未通过 DI 传递 HttpClient 属性 [英] HttpClient properties not being passed with DI

查看:28
本文介绍了未通过 DI 传递 HttpClient 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 ASP.NET Core 5.0 项目,该项目具有访问 API 的服务.根据下面的代码,我希望提供给 ToornamentService 的构造函数的 HttpClient 包含声明的 BaseAddress 和 API 密钥标头.

I'm working on an ASP.NET Core 5.0 project which has a service that accesses an API. Based on the code below, I'd expect the HttpClient supplied to ToornamentService's constructor to contain the declared BaseAddress and API key header.

然而,在调试时,我注意到 HttpClient 从来没有这些.BaseAdress 为空,并且缺少标头.我曾尝试使用 IHttpClientFactory 而不是类型化的客户端,但最终得到相同的结果.

However, when debugging, I noticed that the HttpClient never has either of those. BaseAdress is null, and the header is missing. I've tried using an IHttpClientFactory instead of the typed client, but I end up with the same result.

我做错了什么?

ConfigureServices 方法:

ConfigureServices Method:

public void ConfigureServices(IServiceCollection services)
    {
        //Omitted for brevity
        services.AddHttpClient<ToornamentService>(c =>
        {
            c.BaseAddress = new Uri("https://api.toornament.com/");
            c.DefaultRequestHeaders.Add("X-Api-Key", Configuration["Toornament:ApiKey"]);
        });

        services.AddTransient<ToornamentService>();
    }

ToornamentService 类:

ToornamentService class:

public ToornamentService(HttpClient client)
    {
        Client = client; // client.BaseAddress here is null
    }

推荐答案

删除这一行:services.AddTransient();

当您调用 AddHttpClient 时,它会为您注入临时服务.

When you call AddHttpClient, it injects the service for you as transient.

所以你正在做的是注入它两次.由于您的瞬时注入是最后一次注入,因此它优先于 AddHttpClient 注入.

So what you are doing is injecting it twice. And since your transient injection is the last injection, that takes precedence over the AddHttpClient injection.

这篇关于未通过 DI 传递 HttpClient 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆