实现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
相关产品推荐
相关产品推荐

