AxiosNet.DependencyInjection
1.7.2
dotnet add package AxiosNet.DependencyInjection --version 1.7.2
NuGet\Install-Package AxiosNet.DependencyInjection -Version 1.7.2
<PackageReference Include="AxiosNet.DependencyInjection" Version="1.7.2" />
<PackageVersion Include="AxiosNet.DependencyInjection" Version="1.7.2" />
<PackageReference Include="AxiosNet.DependencyInjection" />
paket add AxiosNet.DependencyInjection --version 1.7.2
#r "nuget: AxiosNet.DependencyInjection, 1.7.2"
#:package AxiosNet.DependencyInjection@1.7.2
#addin nuget:?package=AxiosNet.DependencyInjection&version=1.7.2
#tool nuget:?package=AxiosNet.DependencyInjection&version=1.7.2
AxiosNet.DependencyInjection
.NET 依赖注入扩展(AxiosNet.DependencyInjection) — 为 AxiosNet(含包内声明式客户端,命名空间 AxiosNet.WebAPI)提供 AddAxiosClient / AddApiClient 注册。客户端按单例注册,连接池、拦截器与实例默认值随容器生命周期共享。
运行时依赖只有微软第一方 Microsoft.Extensions.DependencyInjection.Abstractions;与主包同步提供 lib/netstandard2.0 资产,覆盖 .NET Framework 4.7.2+ / .NET Core 2.0+(该资产随主包带入微软第一方 BCL 兼容包,见文末「运行时支持」)。
依赖注入扩展
dotnet add package AxiosNet.DependencyInjection
AddAxiosClient:核心客户端单例
using AxiosNet.DependencyInjection;
builder.Services.AddAxiosClient(config =>
{
config.BaseAddress = "https://api.example.com";
config.Timeout = TimeSpan.FromSeconds(10);
});
// 实例级选项(代理 / 凭据 / Cookie / 重定向次数 / 自建池 / 并发容量)走第二个参数:
// 它们决定连接层与闸门形态,构造期固化,写不进上面的 configure 回调。
builder.Services.AddAxiosClient(
configure: config => config.BaseAddress = "https://api.example.com",
options: new AxiosClientOptions { WithCredentials = true, MaxInFlight = 32 });
// 之后直接注入使用
public sealed class UserService(AxiosClient client)
{
public Task<User> GetAsync(int id) => client.GetAsync<User>($"users/{id}");
}
AddApiClient:声明式客户端单例(三种模式)
using AxiosNet.WebAPI.DependencyInjection;
// 自建模式:自带 BaseAddress 自建底层客户端(与容器里的 AxiosClient 注册互不相干)
// options 同样是底层客户端的实例级选项
builder.Services.AddApiClient("https://api.example.com",
configureDefaults: config => config.Timeout = TimeSpan.FromSeconds(10),
options: new AxiosClientOptions { MaxRedirects = 0, MaxInFlight = 16 },
configure: client => client.CredentialProvider = CredentialProviders.Fixed(token));
// 门面模式:复用容器中已注册的 AxiosClient 单例(需先 AddAxiosClient)
builder.Services.AddApiClient(configure: client =>
client.CredentialProvider = CredentialProviders.Fixed(token));
// 命名模式:多站点(a/b/c)各注册一次,经 IApiClientResolver 按站点名取用(详见下节)
builder.Services.AddApiClient("a", "https://a.example.com");
builder.Services.AddApiClient("b", "https://b.example.com");
多站点:命名注册 + IApiClientResolver
同时对接多个站点时,每个站点调一次 AddApiClient(name, baseAddress, ...)(站点名区分大小写、必须唯一),消费方注入 IApiClientResolver 按键取用:
using AxiosNet.WebAPI.DependencyInjection;
// 注册:每站点自带 BaseAddress、默认值(超时/头/序列化器/连接池)与授权,互不干扰
builder.Services.AddApiClient("a", "https://a.example.com",
configureDefaults: config => config.Timeout = TimeSpan.FromSeconds(10),
configure: client => client.CredentialProvider = CredentialProviders.Fixed(tokenA));
builder.Services.AddApiClient("b", "https://b.example.com",
configure: client => client.CredentialProvider = CredentialProviders.Fixed(tokenB));
// 消费:站点名运行时才知道(来自配置 / 数据库)时用解析器
public sealed class Dispatcher(IApiClientResolver resolver)
{
public Task<AxiosResponse<T>> SendAsync<T>(string site, IApiRequest<T> request)
=> resolver.Get(site).RequestAsync(request);
}
// 消费:站点编译期已知时也可以直接取(每次同一实例)
var a = resolver.Get("a");
if (resolver.TryGet("b", out var b)) { /* b 站点已注册 */ }
Get(name):未注册时抛InvalidOperationException,消息列出全部已注册站点;TryGet不抛Names:已注册站点名,按注册顺序排列(只读副本,外部无法改写解析器状态)- 命名站点只经解析器暴露,不注册未命名的
ApiClient(单站点场景用不带 name 的重载) - 站点名重复在注册期即抛
InvalidOperationException;各站点的底层客户端由解析器持有,随容器退出统一释放 - 解析器释放后调
Get/TryGet抛ObjectDisposedException(已解析与未解析过的站点一致);站点创建失败(configure抛错、凭据提供方解析失败)当场释放已建的连接池并原样透出异常 - .NET 8+ 消费方也可完全用官方键名服务(
AddKeyedSingleton<ApiClient>("a", ...)+[FromKeyedServices("a")]/GetRequiredKeyedService),示例场景 6 有完整演示;两种方案可共存
AddApiInterface:接口级声明注册
把接口级声明(ApiClient.Create<T>() 生成的代理)注册为单例,解析时自动取容器里的 ApiClient:
using AxiosNet.WebAPI.DependencyInjection;
// 默认站点:需先 AddApiClient(...) 注册未命名的 ApiClient
builder.Services.AddApiClient("https://api.example.com");
builder.Services.AddApiInterface<IUserApi>();
// 命名站点:解析 IApiClientResolver.Get("a")
builder.Services.AddApiClient("a", "https://a.example.com");
builder.Services.AddApiInterface<IUserApi>("a");
public sealed class UsersService(IUserApi api)
{
public Task<AxiosResponse<User>> GetAsync(int id) => api.GetAsync(id);
}
- 代理在首次解析时创建并按单例复用(DispatchProxy 生成类型的成本只付一次)
- 容器缺
ApiClient/ 未注册对应站点时,解析抛InvalidOperationException,消息直接给出缺哪一步 - 一个接口只能绑一个站点:
AddApiInterface<IUserApi>()之后再用另一个 name 注册(或反过来)在注册期抛InvalidOperationException,而不是让第二条被TryAddSingleton静默丢弃、请求悄悄打到先注册的站点。同一站点重复注册保持幂等;两个站点要共用同一组方法时定义派生接口(interface IUserApiForB : IUserApi)再注册到另一个站点(继承来的方法同样被代理) - 依赖 Reflection.Emit,仅 JIT:Native AOT 下解析即抛
PlatformNotSupportedException
容器凭据:IApiCredentialProvider 单例自动装配
// 凭据提供方本身也走 DI(真实系统里可从其它服务取令牌 / 刷新)
builder.Services.AddSingleton<IApiCredentialProvider>(
CredentialProviders.Create(async (_, ct) =>
ApiCredential.Token(await TokenService.GetAsync(ct))));
// 未显式设置 CredentialProvider 时自动采用它;configure 里显式设置的优先
builder.Services.AddApiClient("https://api.example.com");
托管令牌由库按 [Authorize] 的 scheme 写头;提供方也可以自己写任意头再返回 ApiCredential.Custom(),或直接给完整头值 ApiCredential.Header(...)。
语义要点
- TryAdd 语义:两者都是「已注册则不重复注册」(保留首次),重复调用不会建出第二个连接池,
configure/configureDefaults的回调也不再执行(不会留下「副作用生效、配置被丢弃」的半生效状态);要替换请先移除原注册 - 多站点(a/b/c):命名重载
AddApiClient(name, baseAddress, ...)+IApiClientResolver(见上节,全 TFM 可用);.NET 8+ 亦可用官方键名服务AddKeyedSingleton<ApiClient>("a", ...)+[FromKeyedServices("a")](示例场景 6) - 生命周期归容器:
using掉注入的客户端不会释放共享实例;单例随容器退出统一释放(自建模式与命名站点经内部持有项/解析器释放连接池) - 门面模式缺注册:容器中没有
AxiosClient时解析ApiClient抛InvalidOperationException(与注册顺序无关) - 完整可运行示例见仓库
samples/AxiosNet.Simple.DependencyInjection(Generic Host,六个场景跑真实 HTTP 往返:核心单例 / 自建 / 门面 / 容器授权 / 命名多站点 / 键名服务)
运行时支持
三目标 netstandard2.0 / net6.0 / net8.0。.NET 6 / 7 / 8 / 9 / 10 / 11 取 lib/net6.0 / lib/net8.0,无第三方运行时依赖;.NET Framework 4.7.2+ / .NET Core 2.0+ / .NET 5 取 lib/netstandard2.0 兼容资产,由 AxiosNet 主包带入微软第一方 BCL 兼容包。三个资产上的 DI 扩展 API 一致。.NET Core 1.0 / 1.1 不在支持范围内(最高只支持 netstandard1.6)。
Dependency injection extensions
dotnet add package AxiosNet.DependencyInjection
AddAxiosClient: core client singleton
using AxiosNet.DependencyInjection;
builder.Services.AddAxiosClient(config =>
{
config.BaseAddress = "https://api.example.com";
config.Timeout = TimeSpan.FromSeconds(10);
});
public sealed class UserService(AxiosClient client)
{
public Task<User> GetAsync(int id) => client.GetAsync<User>($"users/{id}");
}
AddApiClient: declarative client singleton (three modes)
using AxiosNet.WebAPI.DependencyInjection;
// Self-built mode: carries its own BaseAddress, independent of any registered AxiosClient
builder.Services.AddApiClient("https://api.example.com",
configureDefaults: config => config.Timeout = TimeSpan.FromSeconds(10),
configure: client => client.CredentialProvider = CredentialProviders.Fixed(token));
// Facade mode: reuses the registered AxiosClient singleton (call AddAxiosClient first)
builder.Services.AddApiClient(configure: client =>
client.CredentialProvider = CredentialProviders.Fixed(token));
// Named mode: register each site (a/b/c) once and resolve by name via IApiClientResolver (see below)
builder.Services.AddApiClient("a", "https://a.example.com");
builder.Services.AddApiClient("b", "https://b.example.com");
Multiple sites: named registration + IApiClientResolver
When talking to several sites at once, call AddApiClient(name, baseAddress, ...) once per site (names are case-sensitive and must be unique), and inject IApiClientResolver in consumers:
using AxiosNet.WebAPI.DependencyInjection;
// Registration: each site carries its own BaseAddress, defaults (timeout/headers/serializer/pool) and authorization
builder.Services.AddApiClient("a", "https://a.example.com",
configureDefaults: config => config.Timeout = TimeSpan.FromSeconds(10),
configure: client => client.CredentialProvider = CredentialProviders.Fixed(tokenA));
builder.Services.AddApiClient("b", "https://b.example.com",
configure: client => client.CredentialProvider = CredentialProviders.Fixed(tokenB));
// Consumption: when the site is only known at runtime (config / database), use the resolver
public sealed class Dispatcher(IApiClientResolver resolver)
{
public Task<AxiosResponse<T>> SendAsync<T>(string site, IApiRequest<T> request)
=> resolver.Get(site).RequestAsync(request);
}
// Consumption: when the site is known at compile time, take it directly (same instance every time)
var a = resolver.Get("a");
if (resolver.TryGet("b", out var b)) { /* site b is registered */ }
Get(name): throwsInvalidOperationExceptionwhen the name is not registered — the message lists all registered sites;TryGetnever throwsNames: registered site names, in registration order- Named sites are exposed only through the resolver — no unnamed
ApiClientis registered (use the nameless overload for single-site scenarios) - A duplicate name throws
InvalidOperationExceptionat registration time; each site's underlying client is owned by the resolver and released when the container shuts down - On .NET 8+ you can also use the official keyed services end-to-end (
AddKeyedSingleton<ApiClient>("a", ...)+[FromKeyedServices("a")]/GetRequiredKeyedService) — see scenario 6 of the sample; both approaches can coexist
AddApiInterface: interface declaration registration
Register interface declarations (proxies produced by ApiClient.Create<T>()) as singletons; resolution pulls the container's ApiClient:
using AxiosNet.WebAPI.DependencyInjection;
// Default site: register an unkeyed ApiClient first
builder.Services.AddApiClient("https://api.example.com");
builder.Services.AddApiInterface<IUserApi>();
// Named site: resolved via IApiClientResolver.Get("a")
builder.Services.AddApiClient("a", "https://a.example.com");
builder.Services.AddApiInterface<IUserApi>("a");
public sealed class UsersService(IUserApi api)
{
public Task<AxiosResponse<User>> GetAsync(int id) => api.GetAsync(id);
}
- The proxy is created on first resolution and reused as a singleton (DispatchProxy type generation is paid once)
- If the container has no
ApiClientor the named site is missing, resolution throwsInvalidOperationExceptionwith the missing step spelled out - One interface, one site: registering
AddApiInterface<IUserApi>()and then another name (or the other way round) throwsInvalidOperationExceptionat registration time, instead of letting the secondTryAddSingletonbe dropped and requests silently hitting the first site. Repeating the same site is idempotent; to share one method set across two sites, declare a derived interface (interface IUserApiForB : IUserApi) and register it against the other site (inherited methods are proxied too) - Relies on Reflection.Emit, so it is JIT-only: resolution throws
PlatformNotSupportedExceptionunder Native AOT
Credentials from the container
builder.Services.AddSingleton<IApiCredentialProvider>(
CredentialProviders.Create(async (_, ct) =>
ApiCredential.Token(await TokenService.GetAsync(ct))));
builder.Services.AddApiClient("https://api.example.com");
Managed tokens are written by the library using the [Authorize] scheme; a provider may instead write its own headers and return ApiCredential.Custom(), or supply a full header value with ApiCredential.Header(...).
Semantics
- TryAdd semantics: registration is skipped when one already exists (first wins), so repeated calls never create a second connection pool; remove the old registration to replace it
- Multiple sites (a/b/c): the named overload
AddApiClient(name, baseAddress, ...)+IApiClientResolver(see above, works on every TFM); on .NET 8+ the official keyed services (AddKeyedSingleton<ApiClient>("a", ...)+[FromKeyedServices("a")], scenario 6 of the sample) work as well - The container owns the lifetime: disposing an injected client does not release the shared instance; singletons are released when the container shuts down (self-built and named sites release their pools through an internal holder / the resolver)
- Facade mode without a registration: resolving
ApiClientthrowsInvalidOperationExceptionwhen noAxiosClientis registered (order-independent) - Runnable sample:
samples/AxiosNet.Simple.DependencyInjectionin this repository (Generic Host, six scenarios over real HTTP round-trips: core singleton / self-built / facade / container authorization / named multi-site / keyed services)
Runtime support
Tri-target netstandard2.0 / net6.0 / net8.0. .NET 6 / 7 / 8 / 9 / 10 / 11 pick lib/net6.0 / lib/net8.0 and have no third-party runtime dependencies; .NET Framework 4.7.2+ / .NET Core 2.0+ / .NET 5 pick lib/netstandard2.0, the compatibility asset, which pulls in first-party Microsoft BCL compatibility packages through AxiosNet. The DI extension API is identical on all three assets. .NET Core 1.0 / 1.1 is out of scope (it only supports up to netstandard1.6).
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- AxiosNet (>= 1.7.2)
- Microsoft.Bcl.AsyncInterfaces (>= 8.0.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 6.0.0)
- System.Threading.Tasks.Extensions (>= 4.5.4)
-
net6.0
- AxiosNet (>= 1.7.2)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 6.0.0)
-
net8.0
- AxiosNet (>= 1.7.2)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 6.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.7.2 | 51 | 11/21/2026 |
| 1.7.1 | 65 | 11/18/2026 |
| 1.7.0 | 79 | 11/17/2026 |
| 1.6.0 | 100 | 11/13/2026 |
| 1.5.1 | 94 | 11/9/2026 |
| 1.5.0 | 98 | 11/7/2026 |
| 1.4.3 | 102 | 11/5/2026 |
| 1.4.2 | 108 | 11/2/2026 |
| 1.4.1 | 103 | 11/1/2026 |
| 1.4.0 | 108 | 10/31/2026 |
| 1.3.1 | 105 | 10/30/2026 |
| 1.3.0 | 110 | 10/28/2026 |
| 1.2.0 | 111 | 10/26/2026 |
| 1.1.1 | 108 | 10/24/2026 |
| 1.1.0 | 105 | 10/22/2026 |