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

ASP.NET Core 9单例服务中注入的IHttpClientFactory为何为Null?

问题:IHttpClientFactory注入时出现空引用异常

我正尝试实现.NET的IHttpClientFactory模式,当前开发的是ASP.NET Core 9 Web API。

program.cs代码:

var builder = WebApplication.CreateBuilder(args);
var baseAddress = builder.Configuration.GetValue<string>("RuntimeParameters:BaseAddress");
builder.Services.AddControllers();
builder.Services.AddHttpClient("remoteAPI", client =>
    {
        client.BaseAddress = new Uri(baseAddress);        
    }
);

builder.Services.AddSingleton<MySingletonService>();

var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

MySingletonService代码:

public class MySingletonService
{
        private readonly HttpClient _httpClient;
        private readonly IConfiguration _configuration;
        private readonly ILogger<MySingletonService> _logger;

        private class ResponsePayloadModel
        {
            private string grant_Type;
            private MySingletonService parentClass;

            public ResponsePayloadModel(MySingletonService parent)
            {
                parentClass = parent;   
            }
            public string Grant_Type
            {
                get 
                {
                    grant_Type = parentClass._configuration.GetValue<string>("RuntimeParameters:AuthGrant");
                    return grant_Type; 
                }
                set { grant_Type = value; }
            }

            public string Client_Id;
            public string Client_Secret;
            public string Scope;
            public string Code;
        }

        public MySingletonService(
            IConfiguration configuration,
            IHttpClientFactory httpClientFactory,
            ILogger<MySingletonService> logger)
        {
            _configuration = configuration;
            _httpClient = httpClientFactory.CreateClient("remoteAPI");
            _logger = logger;
        }

        public void DoWork(string scope)
        {
            var authEndpoint = "www.example.com/auth";
            var client_Id = "123";
            var client_Secret = "456";

            var payload = new ResponsePayloadModel(new MySingletonService(_configuration, null, null, null))
            {
                Client_Id = client_Id,
                Scope = scope,
                Client_Secret = client_Secret
            };
        }
}

调用CreateClient方法时抛出空引用异常,排查后确认httpClientFactory为Null,请问哪里操作有误?


错误原因及修复方案

1. 核心问题:手动实例化服务导致依赖缺失

在DoWork方法中,你手动创建了MySingletonService的实例:new MySingletonService(_configuration, null, null, null),这里传入的httpClientFactory参数是null。当这个新实例执行构造函数时,调用httpClientFactory.CreateClient("remoteAPI")就会触发空引用异常。

依赖注入的核心是让容器管理服务实例,绝对不要手动new需要依赖注入的服务类。

2. 次要问题:ResponsePayloadModel的设计冗余

ResponsePayloadModel不需要持有MySingletonService的引用,完全可以直接获取配置值并赋值,不需要通过父类间接读取。

修复后的MySingletonService代码

public class MySingletonService
{
    private readonly HttpClient _httpClient;
    private readonly IConfiguration _configuration;
    private readonly ILogger<MySingletonService> _logger;

    private class ResponsePayloadModel
    {
        public string Grant_Type { get; set; }
        public string Client_Id { get; set; }
        public string Client_Secret { get; set; }
        public string Scope { get; set; }
        public string Code { get; set; }
    }

    public MySingletonService(
        IConfiguration configuration,
        IHttpClientFactory httpClientFactory,
        ILogger<MySingletonService> logger)
    {
        _configuration = configuration;
        _httpClient = httpClientFactory.CreateClient("remoteAPI");
        _logger = logger;
    }

    public void DoWork(string scope)
    {
        var authEndpoint = "www.example.com/auth";
        var client_Id = "123";
        var client_Secret = "456";
        // 直接从配置读取Grant_Type
        var grantType = _configuration.GetValue<string>("RuntimeParameters:AuthGrant");

        var payload = new ResponsePayloadModel
        {
            Grant_Type = grantType,
            Client_Id = client_Id,
            Scope = scope,
            Client_Secret = client_Secret
        };

        // 后续可使用_httpClient发送请求,示例:
        // var response = await _httpClient.PostAsJsonAsync(authEndpoint, payload);
    }
}

额外说明

你的program.cs中注册服务的代码是正确的(AddHttpClient和AddSingleton<MySingletonService>),只要确保MySingletonService的实例是由DI容器创建的,依赖就会被正确注入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 02:12:31