h0use
h0use

Reputation: 121

DI of DelegateHandler not working properly

just started working with HttpFactory, and very confused how its DI working, example this line working

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

this doesn't

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

return

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

Same situation here, following code working fine

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

but this doesn't

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

I read a lot of examples of HttpClientFactory usage, my DelegateHandlers from those examples.

What I'm doing wrong?

Upvotes: 5

Views: 4128

Answers (1)

Edward
Edward

Reputation: 29996

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

As this error indicates, you need to register UserAgentDelegatingHandler when you use .AddHttpMessageHandler<UserAgentDelegatingHandler>().

Check AddHttpMessageHandler, and you will find

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

Try to change your code like

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

Upvotes: 11

Related Questions