HttpClientBuilderExtensions.AddAsKeyed Method

Definition

Registers a named HttpClient and the related handler pipeline HttpMessageHandler as keyed services with the client's name as the key, and a lifetime provided in the lifetime parameter. By default, the lifetime is Scoped.

public static Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddAsKeyed (this Microsoft.Extensions.DependencyInjection.IHttpClientBuilder builder, Microsoft.Extensions.DependencyInjection.ServiceLifetime lifetime = Microsoft.Extensions.DependencyInjection.ServiceLifetime.Scoped);
static member AddAsKeyed : Microsoft.Extensions.DependencyInjection.IHttpClientBuilder * Microsoft.Extensions.DependencyInjection.ServiceLifetime -> Microsoft.Extensions.DependencyInjection.IHttpClientBuilder
<Extension()>
Public Function AddAsKeyed (builder As IHttpClientBuilder, Optional lifetime As ServiceLifetime = Microsoft.Extensions.DependencyInjection.ServiceLifetime.Scoped) As IHttpClientBuilder

Parameters

lifetime
ServiceLifetime

Lifetime of the keyed services registered.

Returns

An IHttpClientBuilder that can be used to configure the client.

Remarks

A named client resolved from DI as a keyed service will behave similarly to a client you would create with CreateClient(String). This means that the client will continue reusing the same HttpMessageHandler instance for the duration of HandlerLifetime, and it will continue to use the separate, handler's DI scope instead of the scope it was resolved from.

WARNING: Registering the client as a keyed Transient service will lead to the HttpClient and HttpMessageHandler instances being captured by DI as both implement IDisposable. This might lead to memory leaks if the client is resolved multiple times within a Singleton service.

WARNING: In case of (1) a keyed SingletonHttpClient registration, or (2) a keyed TransientHttpClient injected into a Singleton service, or (3) long-running application scopes, the HttpClient instances will get captured by a singleton or a long-running scope, so they will NOT be able to participate in the handler rotation, which can result in the loss of DNS changes. (This is a similar issue to the one with Typed Clients, that are registered as Transient services.)

If called twice with for a builder with the same name, the lifetime of the keyed service will be updated to the latest used ServiceLifetime value.

If called for a typed client, only the related named client and handler will be registered as keyed. The typed client itself will continue to be registered as a transient service.

If used in conjuction with ConfigureHttpClientDefaults(IServiceCollection, Action<IHttpClientBuilder>), the key AnyKey is used, so any named HttpClient instance will be resolvable as a keyed service (unless explicitly opted-out from the keyed registration via RemoveAsKeyed(IHttpClientBuilder)).

Applies to