Blazor WebClient中AddSingleton对象无法注入到C#类问题求助
问题原因
Blazor的[Inject]属性仅会被框架自动处理组件类(即继承ComponentBase的类,比如你的Index组件,它是和Index.razor对应的partial类,默认继承ComponentBase)。而StudentHandler是普通的C#类,不属于组件,DI容器不会自动识别并处理它的[Inject]属性,所以StudentProperty会是null。
解决方案
推荐使用构造函数注入(符合依赖注入的最佳实践),步骤如下:
1. 修改StudentHandler,改用构造函数注入依赖
namespace MySampleWebClient { public class StudentHandler { private readonly Student _student; // 通过构造函数接收注入的Student实例 public StudentHandler(Student student) { _student = student; } private void GetStudent() { string firstName = _student.FirstName; // 现在可以正常获取值 } } }
2. 将StudentHandler注册到DI容器
在Program.cs中添加注册代码,根据需求选择生命周期(这里和Student保持一致用Singleton):
using MySampleWebClient; Student myStudent = new Student() { FirstName = "TEST First Name", LastName = "TEST Last Name" }; builder.Services.AddSingleton(myStudent); // 新增:注册StudentHandler builder.Services.AddSingleton<StudentHandler>();
3. 在需要使用StudentHandler的地方注入它
比如在组件中使用时,像注入Student一样注入StudentHandler:
// 示例:在Index.razor.cs中注入 using Microsoft.AspNetCore.Components; namespace MySampleWebClient.Pages { public partial class Index { [Inject] protected StudentHandler StudentHandler { get; set; } private void TestHandler() { StudentHandler.GetStudent(); // 调用方法时能正常访问Student实例 } } }
备选方案(不推荐,仅适合组件类)
如果非要使用[Inject]属性,可以让StudentHandler继承ComponentBase,把它当作Blazor组件处理,但这种方式只适合带UI逻辑的类,不适合纯业务处理类:
using Microsoft.AspNetCore.Components; namespace MySampleWebClient { public class StudentHandler : ComponentBase { [Inject] protected Student StudentProperty { get; set; } private void GetStudent() { string firstName = StudentProperty.FirstName; } } }
内容的提问来源于stack exchange,提问作者Ziggler
相关产品推荐
相关产品推荐

