WPF .NET Core 3.1依赖注入调用服务报provider空值异常如何解决
错误根因
你已经将Domain类注册到DI容器中,但跳转页面时选择了手动new Domain(Username)的方式创建实例,完全绕开了DI的依赖注入逻辑,导致Domain类中的Services属性没有被赋值,构造函数执行this.Services.GetRequiredService时,空的Services直接触发了参数为provider的空值异常。
修复方案
方案1(推荐:依赖显式注入)
直接将Domain类需要的依赖放在构造函数参数中,避免在业务代码里手动调用服务获取接口:
- 修改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(); }
- 修改跳转Domain的代码,使用
ActivatorUtilities从DI容器创建带自定义参数的实例:
// 从全局ServiceProvider创建Domain实例,自动注入依赖,手动传入用户名参数 Domain domain = ActivatorUtilities.CreateInstance<Domain>(((App)Application.Current).ServiceProvider, Username); domain.Show(); this.Close();
方案2(兼容原有写法)
如果不想修改Domain类的现有结构,改为在构造函数中先注入IServiceProvider再使用:
- 修改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>(); }
- 跳转代码同上,使用
ActivatorUtilities创建实例即可。
额外注意
你提供的A_UserTenant的Get方法中存在语法错误:var link = $"{link]}Directory/UserTenant/Get"; 中大括号右侧的中括号需要改为大括号,否则会触发编译/字符串拼接错误。
内容的提问来源于stack exchange,提问作者JianYA
相关产品推荐
相关产品推荐

