Blazor WebClient AddSingleton 对象无法注入到 C# 类中

问题描述 投票:0回答:1

我是 Blazor 技术的新手。我正在尝试为 C# 对象添加 AddSingleton,但它不起作用。

在我的 Blazor WebClient 应用程序中,我有 C# 类 Student.cs,如下所示

namespace MySampleWebClient
{
    public class Student
    {
        
        public string FirstName { get; set; }

        public string LastName { get; set; }
        
    }
}

在Program.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

c# singleton blazor-webassembly
1个回答
0
投票

[Inject]
属性只能在您的组件中使用,它已经记录在here

通常,不直接使用此属性。如果基类是 组件需要,并且注入属性也需要 基类,手动添加[Inject]属性:

......

@inject(或 [Inject] 属性)不可用于 服务。必须改用构造函数注入。必需的 通过向服务的构造函数添加参数来添加服务。 当 DI 创建服务时,它会识别它需要的服务 构造函数并相应地提供它们。

github上的相关问题

© www.soinside.com 2019 - 2024. All rights reserved.