You need to enable JavaScript to run this app. WPF .NET Core 3.1依赖注入调用服务报provider空值异常如何解决
优惠活动
大模型
产品
解决方案
定价
更多

WPF .NET Core 3.1依赖注入调用服务报provider空值异常如何解决

错误根因

你已经将Domain类注册到DI容器中,但跳转页面时选择了手动new Domain(Username)的方式创建实例,完全绕开了DI的依赖注入逻辑,导致Domain类中的Services属性没有被赋值,构造函数执行this.Services.GetRequiredService时,空的Services直接触发了参数为provider的空值异常。

修复方案

方案1(推荐:依赖显式注入)

直接将Domain类需要的依赖放在构造函数参数中,避免在业务代码里手动调用服务获取接口:

  1. 修改Domain类构造函数:
private readonly A_UserTenant a_UserTenant;
private readonly A_User a_User;
private string Username = null;

// 依赖直接通过构造函数注入,用户名作为额外参数传入
public Domain(A_UserTenant userTenant, A_User aUser, string Username)
{
    InitializeComponent();
    this.a_UserTenant = userTenant;
    this.a_User = aUser;
    this.Username = Username;
    UsernameTextbox.Text = Username;
    loading = new Loading.Loading();
}
  1. 修改跳转Domain的代码,使用ActivatorUtilities从DI容器创建带自定义参数的实例:
// 从全局ServiceProvider创建Domain实例,自动注入依赖,手动传入用户名参数
Domain domain = ActivatorUtilities.CreateInstance<Domain>(((App)Application.Current).ServiceProvider, Username);
domain.Show();
this.Close();

方案2(兼容原有写法)

如果不想修改Domain类的现有结构,改为在构造函数中先注入IServiceProvider再使用:

  1. 修改Domain类构造函数:
public IServiceProvider Services { get; set; }
private readonly A_UserTenant a_UserTenant;
private readonly A_User a_User;
private string Username = null;

public Domain(IServiceProvider serviceProvider, string Username)
{
    // 先给Services赋值再调用服务获取接口
    this.Services = serviceProvider;
    InitializeComponent();
    this.Username = Username;
    UsernameTextbox.Text = Username;
    loading = new Loading.Loading();
    this.a_UserTenant = this.Services.GetRequiredService<A_UserTenant>();
    this.a_User = this.Services.GetRequiredService<A_User>();
}
  1. 跳转代码同上,使用ActivatorUtilities创建实例即可。

额外注意

你提供的A_UserTenant的Get方法中存在语法错误:var link = $"{link]}Directory/UserTenant/Get"; 中大括号右侧的中括号需要改为大括号,否则会触发编译/字符串拼接错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 12:24:05