MissingMethodException:无法使用 Blazor 和依赖注入动态创建类型的实例

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

当尝试对非无参数构造函数使用依赖项注入时,我在 Blazor 服务器应用程序中遇到“MissingMethodException”

MissingMethodException: Cannot dynamically create an instance of type 'Blazor.Pages.Account.Register'. Reason: No parameterless constructor defined
。这是我迄今为止尝试过的:

我创建了 UserService.cs

using Blazor.API.Model;

namespace Blazor.Services
{
    public class UserService
    {
        private readonly HttpClient _httpClient;
        public UserService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        public async Task<bool> RegisterAsync(RegisterModel registerModel)
        {
            try
            {
                var response = await _httpClient.PostAsJsonAsync("/register", registerModel);
                if (response.IsSuccessStatusCode)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }
    }
}

我已经更新了program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();


builder.Services.AddScoped<HttpClient>(s =>
{
    var httpClient = new HttpClient
    {
        BaseAddress = new Uri(builder.Configuration.GetSection("ApiBaseUrl").Value)
    };
    return httpClient;
});
builder.Services.AddHttpClient();
builder.Services.AddScoped<UserService>();
var app = builder.Build();

此外,当我悬停时,我收到错误“警告 CS8604 'Uri.Uri(string uriString)' 中的参数 'uriString' 可能为空引用参数”

builder.Configuration.GetSection("ApiBaseUrl").Value

和我的register.razor.cs

using Blazor.API.Model;
using Blazor.Services;

namespace Blazor.Pages.Account
{
    public partial class Register
    {
        private UserService UserService { get; set; }
        private bool isRegistering = false;
        private bool registrationSuccessful = false;
        private RegisterModel registerModel = new RegisterModel();
        
        public Register(UserService userService)
        {
            UserService = userService;
        }
        

        private async Task HandleValidSubmit()
        {
            // Start the registration process
            isRegistering = true;

            //send the registration request to the server
            bool registrationResult = await UserService.RegisterAsync(registerModel); 

            // Update the registration state
            registrationSuccessful = registrationResult;

            // Stop the registration process
            isRegistering = false;
        }
    }
}

但是,当我导航到此 Registercomponent 时,我收到“MissingMethodException”错误。我还尝试添加无参数构造函数,但它会导致“不可为空的属性必须包含非空值”警告。

如何解决此问题并正确使用具有非无参数构造函数的 Blazor 组件的依赖注入?

这是我的register.razor

@page "/register"

<h3 class="text-center">Register</h3>
<div class="form-container">
<EditForm Model="@registerModel" OnValidSubmit="HandleValidSubmit" >
    <DataAnnotationsValidator />
    <ValidationSummary />

    <div class="form-group">
        <label for="FirstName" class="form-label">First Name</label>
        <InputText id="FirstName" @bind-Value="registerModel.FirstName" class="form-control" />
        <ValidationMessage For="@(() => registerModel.FirstName)" />
    </div>

    <div class="form-group">
        <label for="LastName" class="form-label">Last Name</label>
        <InputText id="LastName" @bind-Value="registerModel.LastName" class="form-control" />
        <ValidationMessage For="@(() => registerModel.LastName)" />
    </div>

    <div class="form-group">
        <label for="Email" class="form-label">Email</label>
        <InputText id="Email" @bind-Value="registerModel.Email" class="form-control" />
        <ValidationMessage For="@(() => registerModel.Email)" />
    </div>

    <div class="form-group">
        <label for="PhoneNumber" class="form-label">Phone Number</label>
        <InputText id="PhoneNumber" @bind-Value="registerModel.PhoneNumber" class="form-control" />
        <ValidationMessage For="@(() => registerModel.PhoneNumber)" />
    </div>

    <div class="form-group">
        <label for="Password" class="form-label">Password</label>
        <InputText id="Password" @bind-Value="registerModel.Password" class="form-control" type="password" />
        <ValidationMessage For="@(() => registerModel.Password)" />
    </div>

        <div class="text-center">
            <button type="submit" class="btn btn-primary" disabled="@isRegistering">
                @if (isRegistering)
                {
                    <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                    <text>Registering...</text>
                }
                else if (registrationSuccessful)
                {
                    <text>Registration Successful</text>
                }
                else
                {
                    <text>Register</text>
                }
            </button>
        </div>
        <p class="text-center mt-3">
        Already have an account? <a href="/login">Login here</a>
    </p>
</EditForm>
</div>

@code {
   
}

和我的appSetting.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ApiBaseUrl": "https://localhost:44330/"
}

我是 Blazor Server 应用程序的初学者,目前正在尝试学习如何在 Blazor Server 应用程序中连接 API 并与之交互。具体来说,我正在致力于实现用户注册和登录功能。但是,我在设置 HttpClient 和建立注册过程的正确流程方面遇到了困难,如本文所述。

c# .net blazor httpclient missingmethodexception
1个回答
0
投票

可以通过使用文件顶部的

#nullable disable
注释或在设置服务时禁用 null 错误。

您尝试通过 Register 组件的构造函数注入依赖项。在 Blazor 中,组件由框架激活,框架期望它们具有无参数构造函数。这允许 Blazor 根据需要动态创建组件的实例。如果您提供带参数的构造函数,但没有提供无参数构造函数,Blazor 将不知道如何创建该组件的实例,从而导致 MissingMethodException。

MissingMethodException:无法动态创建类型的实例 'Blazor.Pages.Account.Register'。原因:没有无参数构造函数 定义的。错误。

您可以使用属性注入,而不是对 Register 组件使用构造函数注入。

    [Inject]
    public UserService UserService { get; set; }

您的 register.razor 文件缺少定义其支持 C# 类的 @code 块。这会将其与 Razor UI 集成。注意,为空!用于避免空错误,而不是下面代码中的可空注释。

@code {
[Inject]
public UserService UserService { get; set; } = null!;

private bool isRegistering = false;
private bool registrationSuccessful = false;
private RegisterModel registerModel = new RegisterModel();

private async Task HandleValidSubmit()
{
    isRegistering = true;
    bool registrationResult = await UserService.RegisterAsync(registerModel);
    registrationSuccessful = registrationResult;
    isRegistering = false;
} }

希望有帮助!

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