Skip to content

Commit 873c8bd

Browse files
authored
feat: keyed refit generated client DI registration (#2297)
* feat: add AddKeyedRefitGeneratedClient for keyed generated-only DI parity AddRefitGeneratedClient<T> had no keyed counterpart, so Native AOT and trimmed apps could not register the same Refit interface more than once with different configuration without falling back to the reflection path. Adds AddKeyedRefitGeneratedClient<T> on IServiceCollection mirroring all five AddRefitGeneratedClient<T> overloads with a leading serviceKey. The client and its SettingsFor<T> register as keyed services, the underlying HttpClient name defaults to UniqueName.ForType<T>(serviceKey), and handler composition follows AddKeyedRefitClient so both keyed paths behave alike. No reflection fallback and no RequiresUnreferencedCode annotation. Purely additive. * Remove note changes in breaking-changes since it is not really breaking
1 parent ee87983 commit 873c8bd

14 files changed

Lines changed: 528 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2570,6 +2570,23 @@ services.AddRefitGeneratedClient<IWebApi>(provider => new RefitSettings { /* con
25702570
services.AddRefitGeneratedClient<IWebApi>(settings, "my-named-client");
25712571
```
25722572

2573+
`AddKeyedRefitGeneratedClient<T>` is the keyed counterpart, mirroring `AddKeyedRefitClient<T>` for the generated-only
2574+
path. It registers the client (and its `SettingsFor<T>`) under a service key so the same interface can be registered
2575+
more than once with different configuration, and each key gets its own named `HttpClient`:
2576+
2577+
```csharp
2578+
services.AddKeyedRefitGeneratedClient<IWebApi>("primary")
2579+
.ConfigureHttpClient(c => c.BaseAddress = new Uri("https://primary.example.com"));
2580+
services.AddKeyedRefitGeneratedClient<IWebApi>("secondary", settings)
2581+
.ConfigureHttpClient(c => c.BaseAddress = new Uri("https://secondary.example.com"));
2582+
2583+
// resolve with the key
2584+
var primary = provider.GetRequiredKeyedService<IWebApi>("primary");
2585+
```
2586+
2587+
The same overload shapes are available as the non-keyed helper - settings, a settings factory resolved from the
2588+
container, and a custom `HttpClient` name - each taking the service key as the first argument.
2589+
25732590
If no source-generated client exists for the interface, resolving it throws an `InvalidOperationException` that points
25742591
you back to the generator output - the registration never silently falls back to reflection.
25752592

‎src/Refit.HttpClientFactory/HttpClientFactoryCore.cs‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,56 @@ internal static IHttpClientBuilder AddRefitGeneratedClientCore<T>(
304304
serviceProvider.GetRequiredService<SettingsFor<T>>().Settings ?? new RefitSettings()));
305305
}
306306

307+
/// <summary>Registers a strongly typed, keyed, source-generated Refit client without any reflection fallback.</summary>
308+
/// <typeparam name="T">The Refit interface type to register.</typeparam>
309+
/// <param name="services">The service collection to register into.</param>
310+
/// <param name="serviceKey">The key under which the client is registered.</param>
311+
/// <param name="settings">A factory that produces the Refit settings, or null.</param>
312+
/// <param name="httpClientName">A name for the underlying HTTP client, or null.</param>
313+
/// <returns>The HTTP client builder for further configuration.</returns>
314+
[SuppressMessage(
315+
"Design",
316+
"SST2307:Generic method type parameters should be inferable from the parameters",
317+
Justification = "The Refit interface type is intentionally specified explicitly by callers.")]
318+
internal static IHttpClientBuilder AddKeyedRefitGeneratedClientCore<T>(
319+
IServiceCollection services,
320+
object? serviceKey,
321+
Func<IServiceProvider, RefitSettings?>? settings,
322+
string? httpClientName)
323+
where T : class
324+
{
325+
ArgumentExceptionHelper.ThrowIfNull(services);
326+
327+
ArgumentExceptionHelper.ThrowIfNull(serviceKey);
328+
329+
// register settings
330+
_ = services.AddKeyedSingleton(
331+
serviceKey,
332+
(provider, _) => new SettingsFor<T>(settings?.Invoke(provider)));
333+
334+
// create HttpClientBuilder
335+
var builder = services.AddHttpClient(httpClientName ?? UniqueName.ForType<T>(serviceKey));
336+
337+
// configure primary and additional handlers from the keyed settings
338+
ConfigureKeyedHandlers(
339+
builder,
340+
serviceProvider => serviceProvider.GetRequiredKeyedService<SettingsFor<T>>(serviceKey));
341+
342+
// add keyed typed client backed by the source generator only; throws clearly if no generated client exists
343+
_ = builder.Services.AddKeyedTransient(
344+
serviceKey,
345+
(s, _) =>
346+
{
347+
var httpClientFactory = s.GetRequiredService<IHttpClientFactory>();
348+
var httpClient = httpClientFactory.CreateClient(builder.Name);
349+
return RestService.ForGenerated<T>(
350+
httpClient,
351+
s.GetRequiredKeyedService<SettingsFor<T>>(serviceKey).Settings ?? new RefitSettings());
352+
});
353+
354+
return builder;
355+
}
356+
307357
/// <summary>Resolves and caches the open generic <see cref="RequestBuilder.ForType{T}(RefitSettings?)"/> method.</summary>
308358
/// <returns>The open generic <c>RequestBuilder.ForType</c> method definition.</returns>
309359
[RequiresUnreferencedCode("Resolving RequestBuilder.ForType by reflection requires method metadata to be available at runtime.")]

‎src/Refit.HttpClientFactory/HttpClientFactoryExtensions.ServiceCollection.cs‎

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -661,5 +661,140 @@ public IHttpClientBuilder AddRefitGeneratedClient<T>(
661661
settingsAction,
662662
httpClientName);
663663
}
664+
665+
/// <summary>
666+
/// Adds a source-generated Refit client to the dependency injection container under the specified
667+
/// service key, without any reflection fallback, making it safe for Native AOT and trimming. The client
668+
/// is built through <c>RestService.ForGenerated&lt;T&gt;</c>; if no generated implementation exists for
669+
/// <typeparamref name="T"/>, resolving the client throws an <see cref="InvalidOperationException"/>. The
670+
/// usual HttpClientFactory features (base address, handlers, resilience pipelines) remain available on
671+
/// the returned builder.
672+
/// </summary>
673+
/// <typeparam name="T">The type of the Refit interface.</typeparam>
674+
/// <param name="serviceKey">A key used to associate with the specific Refit client instance.</param>
675+
/// <returns>The HTTP client builder for chaining.</returns>
676+
[SuppressMessage(
677+
"Design",
678+
"SST2307:Generic method type parameters should be inferable from the parameters",
679+
Justification = "The Refit interface type is intentionally specified explicitly by callers.")]
680+
public IHttpClientBuilder AddKeyedRefitGeneratedClient<T>(object? serviceKey)
681+
where T : class
682+
{
683+
ArgumentExceptionHelper.ThrowIfNull(services);
684+
685+
ArgumentExceptionHelper.ThrowIfNull(serviceKey);
686+
687+
return HttpClientFactoryCore.AddKeyedRefitGeneratedClientCore<T>(
688+
services,
689+
serviceKey,
690+
static _ => null,
691+
null);
692+
}
693+
694+
/// <summary>Adds a source-generated Refit client to the dependency injection container under the specified service key, without any reflection fallback.</summary>
695+
/// <typeparam name="T">The type of the Refit interface.</typeparam>
696+
/// <param name="serviceKey">A key used to associate with the specific Refit client instance.</param>
697+
/// <param name="settings">The settings used to configure the instance.</param>
698+
/// <returns>The HTTP client builder for chaining.</returns>
699+
[SuppressMessage(
700+
"Design",
701+
"SST2307:Generic method type parameters should be inferable from the parameters",
702+
Justification = "The Refit interface type is intentionally specified explicitly by callers.")]
703+
public IHttpClientBuilder AddKeyedRefitGeneratedClient<T>(
704+
object? serviceKey,
705+
RefitSettings? settings)
706+
where T : class
707+
{
708+
ArgumentExceptionHelper.ThrowIfNull(services);
709+
710+
ArgumentExceptionHelper.ThrowIfNull(serviceKey);
711+
712+
return HttpClientFactoryCore.AddKeyedRefitGeneratedClientCore<T>(
713+
services,
714+
serviceKey,
715+
_ => settings,
716+
null);
717+
}
718+
719+
/// <summary>Adds a source-generated Refit client to the dependency injection container under the specified service key, without any reflection fallback.</summary>
720+
/// <typeparam name="T">The type of the Refit interface.</typeparam>
721+
/// <param name="serviceKey">A key used to associate with the specific Refit client instance.</param>
722+
/// <param name="settings">The settings used to configure the instance.</param>
723+
/// <param name="httpClientName">Allows the name of the underlying HttpClient to be changed.</param>
724+
/// <returns>The HTTP client builder for chaining.</returns>
725+
[SuppressMessage(
726+
"Design",
727+
"SST2307:Generic method type parameters should be inferable from the parameters",
728+
Justification = "The Refit interface type is intentionally specified explicitly by callers.")]
729+
public IHttpClientBuilder AddKeyedRefitGeneratedClient<T>(
730+
object? serviceKey,
731+
RefitSettings? settings,
732+
string? httpClientName)
733+
where T : class
734+
{
735+
ArgumentExceptionHelper.ThrowIfNull(services);
736+
737+
ArgumentExceptionHelper.ThrowIfNull(serviceKey);
738+
739+
return HttpClientFactoryCore.AddKeyedRefitGeneratedClientCore<T>(
740+
services,
741+
serviceKey,
742+
_ => settings,
743+
httpClientName);
744+
}
745+
746+
/// <summary>Adds a source-generated Refit client to the dependency injection container under the specified service key, without any reflection fallback.</summary>
747+
/// <typeparam name="T">The type of the Refit interface.</typeparam>
748+
/// <param name="serviceKey">A key used to associate with the specific Refit client instance.</param>
749+
/// <param name="settingsAction">An action used to configure the Refit settings from the service provider.</param>
750+
/// <returns>The HTTP client builder for chaining.</returns>
751+
[System.Runtime.CompilerServices.OverloadResolutionPriority(1)]
752+
[SuppressMessage(
753+
"Design",
754+
"SST2307:Generic method type parameters should be inferable from the parameters",
755+
Justification = "The Refit interface type is intentionally specified explicitly by callers.")]
756+
public IHttpClientBuilder AddKeyedRefitGeneratedClient<T>(
757+
object? serviceKey,
758+
Func<IServiceProvider, RefitSettings?>? settingsAction)
759+
where T : class
760+
{
761+
ArgumentExceptionHelper.ThrowIfNull(services);
762+
763+
ArgumentExceptionHelper.ThrowIfNull(serviceKey);
764+
765+
return HttpClientFactoryCore.AddKeyedRefitGeneratedClientCore<T>(
766+
services,
767+
serviceKey,
768+
settingsAction,
769+
null);
770+
}
771+
772+
/// <summary>Adds a source-generated Refit client to the dependency injection container under the specified service key, without any reflection fallback.</summary>
773+
/// <typeparam name="T">The type of the Refit interface.</typeparam>
774+
/// <param name="serviceKey">A key used to associate with the specific Refit client instance.</param>
775+
/// <param name="settingsAction">An action used to configure the Refit settings from the service provider.</param>
776+
/// <param name="httpClientName">Allows the name of the underlying HttpClient to be changed.</param>
777+
/// <returns>The HTTP client builder for chaining.</returns>
778+
[System.Runtime.CompilerServices.OverloadResolutionPriority(1)]
779+
[SuppressMessage(
780+
"Design",
781+
"SST2307:Generic method type parameters should be inferable from the parameters",
782+
Justification = "The Refit interface type is intentionally specified explicitly by callers.")]
783+
public IHttpClientBuilder AddKeyedRefitGeneratedClient<T>(
784+
object? serviceKey,
785+
Func<IServiceProvider, RefitSettings?>? settingsAction,
786+
string? httpClientName)
787+
where T : class
788+
{
789+
ArgumentExceptionHelper.ThrowIfNull(services);
790+
791+
ArgumentExceptionHelper.ThrowIfNull(serviceKey);
792+
793+
return HttpClientFactoryCore.AddKeyedRefitGeneratedClientCore<T>(
794+
services,
795+
serviceKey,
796+
settingsAction,
797+
httpClientName);
798+
}
664799
}
665800
}

‎src/Refit.HttpClientFactory/PublicAPI/net10.0/PublicAPI.txt‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,13 @@ public static class HttpClientFactoryExtensions
7272
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Registering Refit clients with HttpClientFactory requires reflected interface and request metadata.")]
7373
[System.Runtime.CompilerServices.OverloadResolutionPriority(1)]
7474
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddKeyedRefitClient<T>(object? serviceKey, System.Func<System.IServiceProvider, Refit.RefitSettings?>? settingsAction, string? httpClientName) where T : class { }
75+
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddKeyedRefitGeneratedClient<T>(object? serviceKey) where T : class { }
76+
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddKeyedRefitGeneratedClient<T>(object? serviceKey, Refit.RefitSettings? settings) where T : class { }
77+
[System.Runtime.CompilerServices.OverloadResolutionPriority(1)]
78+
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddKeyedRefitGeneratedClient<T>(object? serviceKey, System.Func<System.IServiceProvider, Refit.RefitSettings?>? settingsAction) where T : class { }
79+
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddKeyedRefitGeneratedClient<T>(object? serviceKey, Refit.RefitSettings? settings, string? httpClientName) where T : class { }
80+
[System.Runtime.CompilerServices.OverloadResolutionPriority(1)]
81+
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddKeyedRefitGeneratedClient<T>(object? serviceKey, System.Func<System.IServiceProvider, Refit.RefitSettings?>? settingsAction, string? httpClientName) where T : class { }
7582
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Registering Refit clients by Type with HttpClientFactory requires runtime generic type and method instantiation.")]
7683
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Registering Refit clients with HttpClientFactory requires reflected interface and request metadata.")]
7784
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddRefitClient(System.Type refitInterfaceType) { }

‎src/Refit.HttpClientFactory/PublicAPI/net11.0/PublicAPI.txt‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,13 @@ public static class HttpClientFactoryExtensions
7272
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Registering Refit clients with HttpClientFactory requires reflected interface and request metadata.")]
7373
[System.Runtime.CompilerServices.OverloadResolutionPriority(1)]
7474
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddKeyedRefitClient<T>(object? serviceKey, System.Func<System.IServiceProvider, Refit.RefitSettings?>? settingsAction, string? httpClientName) where T : class { }
75+
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddKeyedRefitGeneratedClient<T>(object? serviceKey) where T : class { }
76+
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddKeyedRefitGeneratedClient<T>(object? serviceKey, Refit.RefitSettings? settings) where T : class { }
77+
[System.Runtime.CompilerServices.OverloadResolutionPriority(1)]
78+
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddKeyedRefitGeneratedClient<T>(object? serviceKey, System.Func<System.IServiceProvider, Refit.RefitSettings?>? settingsAction) where T : class { }
79+
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddKeyedRefitGeneratedClient<T>(object? serviceKey, Refit.RefitSettings? settings, string? httpClientName) where T : class { }
80+
[System.Runtime.CompilerServices.OverloadResolutionPriority(1)]
81+
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddKeyedRefitGeneratedClient<T>(object? serviceKey, System.Func<System.IServiceProvider, Refit.RefitSettings?>? settingsAction, string? httpClientName) where T : class { }
7582
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Registering Refit clients by Type with HttpClientFactory requires runtime generic type and method instantiation.")]
7683
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Registering Refit clients with HttpClientFactory requires reflected interface and request metadata.")]
7784
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddRefitClient(System.Type refitInterfaceType) { }

‎src/Refit.HttpClientFactory/PublicAPI/net462/PublicAPI.txt‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@ public static class HttpClientFactoryExtensions
3131
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddKeyedRefitClient<T>(object? serviceKey, System.Func<System.IServiceProvider, Refit.RefitSettings?>? settingsAction) where T : class { }
3232
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddKeyedRefitClient<T>(object? serviceKey, Refit.RefitSettings? settings, string? httpClientName) where T : class { }
3333
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddKeyedRefitClient<T>(object? serviceKey, System.Func<System.IServiceProvider, Refit.RefitSettings?>? settingsAction, string? httpClientName) where T : class { }
34+
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddKeyedRefitGeneratedClient<T>(object? serviceKey) where T : class { }
35+
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddKeyedRefitGeneratedClient<T>(object? serviceKey, Refit.RefitSettings? settings) where T : class { }
36+
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddKeyedRefitGeneratedClient<T>(object? serviceKey, System.Func<System.IServiceProvider, Refit.RefitSettings?>? settingsAction) where T : class { }
37+
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddKeyedRefitGeneratedClient<T>(object? serviceKey, Refit.RefitSettings? settings, string? httpClientName) where T : class { }
38+
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddKeyedRefitGeneratedClient<T>(object? serviceKey, System.Func<System.IServiceProvider, Refit.RefitSettings?>? settingsAction, string? httpClientName) where T : class { }
3439
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddRefitClient(System.Type refitInterfaceType) { }
3540
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddRefitClient(System.Type refitInterfaceType, Refit.RefitSettings? settings) { }
3641
public Microsoft.Extensions.DependencyInjection.IHttpClientBuilder AddRefitClient(System.Type refitInterfaceType, System.Func<System.IServiceProvider, Refit.RefitSettings?>? settingsAction) { }

0 commit comments

Comments
 (0)
⌂ 换网址