提问人:Ziggler 提问时间:11/16/2023 更新时间:11/17/2023 访问量:26
Blazor WebClient AddSingleton 对象无法注入到 C# 类中
Blazor WebClient AddSingleton object cannot inject into C# class
问:
我是 Blazor 技术的新手。我正在尝试将 AddSingleton 用于 C# 对象,但它不起作用。
在我的 Blazor WebClient 应用程序中,我有如下所示的 C# 类 Student.cs
namespace MySampleWebClient
{
public class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
在程序.cs中
using MySampleWebClient;
Student myStudent = new Student()
{
FirstName = "TEST First Name",
LastName = "TEST Last Name"
};
builder.Services.AddSingleton(myStudent);
我有C#类StudentHandler.cs,如下所示
using Microsoft.AspNetCore.Components;
namespace MySampleWebClient
{
public class StudentHandler
{
[Inject]
protected Student StudentProperty { get; set; }
private void GetStudent()
{
string firstName = StudentProperty.FirstName; //Here StudentProperty is NULL
}
}
}
在_Import.razor中,我有如下
@using MySampleWebClient
但是在Index.razor.cs中一切看起来都不错,如下所示
using Microsoft.AspNetCore.Components;
namespace MySampleWebClient.Pages
{
public partial class Index
{
[Inject]
protected Student StudentProperty { get; set; }
private void TestStudent()
{
string firstName = StudentProperty.FirstName; //All good here
}
}
}
我不知道为什么我无法将 Student 注入 StudentHandler.cs
答:
0赞
Ruikai Feng
11/17/2023
#1
通常,不直接使用此属性。如果基类是 组件是必需的,注入属性也是必需的 基类,手动添加 [Inject] 属性:
......
@inject(或 [Inject] 属性)不适用于 服务业。必须改用构造函数注入。必填 通过向服务的构造函数添加参数来添加服务。 当 DI 创建服务时,它会识别 构造函数并相应地提供它们。
github 上的相关问题
评论
0赞
Ziggler
11/18/2023
为什么 Inject 适用于 Index.razor.cs,但不适用于 StudentHandler.cs。我需要阅读您发送的链接。谢谢
评论