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

实现IHttpClientFactory时遇System.ArgumentNullException(参数'factory'为空)

问题分析与解决思路

核心原因

你的CustomersHome组件同时定义了无参构造函数和接收IHttpClientFactory的构造函数,Blazor在实例化组件时会优先调用无参构造,导致_httpClientFactory字段始终为null,最终调用CreateClient()时触发ArgumentNullException。

修复方案

方案1:移除无参构造函数

Blazor组件的依赖注入只能通过带参数的构造函数完成,删除无参构造后,框架会自动注入IHttpClientFactory:

public partial class CustomersHome
{
    private readonly IHttpClientFactory _httpClientFactory;

    // 移除无参构造函数
    public CustomersHome(IHttpClientFactory httpClientFactory) => _httpClientFactory = httpClientFactory;

    public IEnumerable<Quotation> customerQuotations = Array.Empty<Quotation>();

    public async Task CustomerRowSelectHandler(RowSelectEventArgs<Customer> args)
    {
        await GetCustomerQuotes(args.Data.customerId);
    }

    public async ValueTask GetCustomerQuotes(int customerId)
    {
        string url = string.Format(@"https://my.server.dns/quotations/customer/{0}", customerId);

        var httpRequestMessage = new HttpRequestMessage(
            HttpMethod.Get,
            url)
        {
            Headers =
            {
                { HeaderNames.Accept, "application/vnd.github.v3+json" },
                { HeaderNames.UserAgent, "HttpRequestsSample" }
            }
        };
        
        var httpClient = _httpClientFactory.CreateClient();
        HttpResponseMessage response = await httpClient.SendAsync(httpRequestMessage);
        if (response.IsSuccessStatusCode)
        {
            customerQuotations = await response.Content.ReadFromJsonAsync<IEnumerable<Quotation>>() ?? Enumerable.Empty<Quotation>();
        }
    }
}

方案2:使用属性注入(替代构造注入)

如果需要保留无参构造函数,可以通过[Inject]属性实现依赖注入,无需手动编写构造函数:

public partial class CustomersHome
{
    // 使用[Inject]标记字段,框架自动注入
    [Inject]
    private IHttpClientFactory _httpClientFactory { get; set; } = null!;

    public CustomersHome() { }

    public IEnumerable<Quotation> customerQuotations = Array.Empty<Quotation>();

    public async Task CustomerRowSelectHandler(RowSelectEventArgs<Customer> args)
    {
        await GetCustomerQuotes(args.Data.customerId);
    }

    public async ValueTask GetCustomerQuotes(int customerId)
    {
        string url = string.Format(@"https://my.server.dns/quotations/customer/{0}", customerId);

        var httpRequestMessage = new HttpRequestMessage(
            HttpMethod.Get,
            url)
        {
            Headers =
            {
                { HeaderNames.Accept, "application/vnd.github.v3+json" },
                { HeaderNames.UserAgent, "HttpRequestsSample" }
            }
        };
        
        var httpClient = _httpClientFactory.CreateClient();
        HttpResponseMessage response = await httpClient.SendAsync(httpRequestMessage);
        if (response.IsSuccessStatusCode)
        {
            customerQuotations = await response.Content.ReadFromJsonAsync<IEnumerable<Quotation>>() ?? Enumerable.Empty<Quotation>();
        }
    }
}

额外注意事项

  • 确保Program.cs中已经正确注册IHttpClientFactory:builder.Services.AddHttpClient();(你已经完成这一步)
  • 代码中\"是多余的转义字符,直接使用双引号即可
  • 组件中更新customerQuotations后,记得调用StateHasChanged()触发UI刷新(如果需要实时显示数据)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 13:21:24