Warm tip: This article is reproduced from serverfault.com, please click

c#-从依赖注入配置进行依赖调用

(c# - Make dependency calls from dependency injection configuration)

发布于 2021-10-14 09:03:41

我的需要是立即注入一个 HttpClient 并准备好使用。但需要注意的是 HttpClient 需要Authorization设置标头,为此我需要再进行一次调用,获取令牌。我设法在初创公司的 RegisterServices 中完成了所有这些配置,但我怀疑这是否是个好主意。

services.AddHttpClient("OidcClient", (isp, client) =>
{
    var options = isp.GetRequiredService<IOptions<MyConfig>>().Value;
    client.BaseAddress = new Uri(options.OidcUrl);
});

services.AddHttpClient("MyClient", (isp, client) =>
{
    var options = isp.GetRequiredService<IOptions<MyConfig>>().Value;
    var oidcClient = isp.GetRequiredService<IHttpClientFactory>().CreateClient("OidcClient");
    var data = new Dictionary<string, string>
    {
        {"client_id", options.ClientId},
        {"client_secret", options.ClientSecret}
    };

    var request = new HttpRequestMessage(HttpMethod.Post, "/connect/token") { Content = new FormUrlEncodedContent(data) };
    var response = oidcClient.SendAsync(request).Result;

    var token = response.Content.ReadFromJsonAsync<TokenResponse>().Result;

    client.BaseAddress = new Uri(options.Url);
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Token);
});

然后它被正确地注入到我的代码中,我可以使用带有授权标头的客户端。

所以,我的担忧是:

  • 在依赖配置中进行 HTTP 调用是否正常?
  • 还没有找到比.Result异步调用更好的方法,还有其他选择吗?

主要问题是:在 DI 配置中进行依赖调用是一个“好主意”吗?

Questioner
Anthony
Viewed
0
TheGeneral 2021-10-14 19:32:21

尽管 CodeCasters 的回答非常正确。理想情况下,你会为此任务使用委托处理程序。

它允许你在各个阶段拦截请求并在请求中添加所需的任何人工制品,在你的情况下授权属性,它也是异步友好的。

但是请注意错误以及返回给调用者的内容。以免给消费者带来惊喜