You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Lambda实现工厂中访问已注册的HttpClient服务?

问题描述

我一直尝试研究该问题但毫无进展,参考了几个相关问题,但内容有些令人困惑,且没有找到完全匹配我需求的示例。

我编写了如下类似代码:

Middleware.cs

public static IServiceCollection UseAPI(this IServiceCollection services, string key, string username, bool test = false)
{
    services.AddHttpClient<ApiClient>(client =>
    {
        // ... 根据test设置BaseAddress,添加认证头等
    });
    return services.AddScoped<ApiClient>(x =>
    {
        var service = x.GetRequiredService<HttpClient>();
        var client = new ApiClient(service);
        client.Configure(key);
        return client;
    });
}

Program.cs

services.UseAPI(_settings.Key, _settings.Username, _settings.IsTest);

ApiClient.cs

public class ApiClient
{
    private readonly HttpClient httpClient;
    private string Key;
    public ApiClient(HttpClient _httpClient)
    {
        httpClient = _httpClient;
    }

    public void Configure(string key)
    {
        Key = key;
    }
}

其中Key值用于内容签名流程,无法添加到默认请求头中。我希望在Lambda实现的工厂中获取已注册的HttpClient服务,同时不想依赖配置以保证包的可移植性,但目前无法实现该需求。

内容的提问来源于stack exchange,提问作者ahwm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 00:30:01