c# - DelegateHandler 的 DI 无法正常工作

标签 c# asp.net-core httpclientfactory

刚开始使用 HttpFactory,并且非常困惑它的 DI 是如何工作的,例如这一行工作

services.AddHttpClient<IMyClient, MyClient>()
   .AddHttpMessageHandler(s => new UserAgentDelegatingHandler());

这不是

services.AddHttpClient<IMyClient, MyClient>()
  .AddHttpMessageHandler<UserAgentDelegatingHandler>();

返回

"Message: System.InvalidOperationException : No service for type 'UserAgentDelegatingHandler' has been registered."

同样的情况,下面的代码工作正常

services.AddHttpContextAccessor();
services.AddHttpClient<IMyClient, MyClient>()
   .AddHttpMessageHandler(s => new CookieDelegateHandler(s.GetRequiredService<IHttpContextAccessor>()));

但这不是

services.AddHttpContextAccessor();
services.AddHttpClient<IMyClient, MyClient>()
   .AddHttpMessageHandler<CookieDelegateHandler>();

我阅读了很多 HttpClientFactory 用法示例,我的 DelegateHandlers 来自这些示例。

我做错了什么?

最佳答案

return "Message: System.InvalidOperationException : No service for type 'UserAgentDelegatingHandler' has been registered."

如该错误所示,您需要注册 UserAgentDelegatingHandler当你使用 .AddHttpMessageHandler<UserAgentDelegatingHandler>() .

检查 AddHttpMessageHandler ,你会发现

The type of the DelegatingHandler. The handler type must be registered as a transient service.

试着改变你的代码

services.AddTransient<UserAgentDelegatingHandler>();
services.AddHttpClient<IMyClient, MyClient>()
        .AddHttpMessageHandler<UserAgentDelegatingHandler>();

关于c# - DelegateHandler 的 DI 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55738010/

相关文章:

c# - C# 中的 FILETIME 舍入以适应 FAT 舍入

C# 和 VB.NET 引发事件差异

c# - 线程逐渐增加处理器使用率

asp.net-core - 是否可以公开来自 Asp.Net Core Identity 的安全标记作为 OIDC 的声明

c# - ModelStateDictionairy 格式错误的 json Web api

c# - 如何将 httpclienthandler 显式传递给 httpclientfactory?

c# - InvalidCastException : Cannot cast from source type to destination type.(Unity c#,foreach 列表循环)

c# - 使用 Autofac 的 ASP.NET Core v2.0 的 SignalR 依赖注入(inject)

javascript - 是否可以将删除/放置请求发送到 Azure AD 安全 api 或使用 aadHttpClientFactory 以字符串形式获取 jwt token