[英]How do I use custom model binder that supports dependency injection in ASP.NET Core?
[英]How do I properly use dependency injection to include asp.net core identity UserManager on a Blazor component?
如何正確使用依賴注入在 Blazor 組件上包含 asp.net 核心標識 UserManager?
我將 Identity 搭建到項目中,創建了一個自定義字段,並編輯了 Identity 頁面,以便在注冊和個人資料頁面期間顯示和編輯此字段。
由於這些頁面主要用於登錄用戶,因此我需要為管理員構建一個頁面來查看和編輯用戶。
我創建了一個 Blazor 頁面並從“Index.cshtml.cs”復制了這段代碼,該代碼也出現在互聯網上:
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
public IndexModel(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
我在這里使用了指南: Micosoft Docs ,創建了一個 Razor 組件來指定該組件的基本 class。 由於它是服務器端 Blazor 應用程序,我認為這應該沒問題,但事實並非如此。
我的 class 代碼是:
namespace UsersComponent
{
public class UsersBase : ComponentBase
{
private readonly UserManager<ApplicationUser> _userManager;
public UsersBase(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
我在依賴注入時收到此錯誤:
public UsersBase(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
錯誤是這樣的:
CS7036 There is no argument given that corresponds to the required formal parameter 'userManager' of 'UsersBase.UsersBase(UserManager<ApplicationUser>)'
誰能指出我減輕這個錯誤? 我將不勝感激。
我假設您在Program.cs
中使用類似以下內容: builder.Services.AddDefaultIdentity<ApplicationUser>...
對於 razor 組件中的注入,您需要在屬性上使用[Inject]
屬性或在 razor 標記區域中使用 @inject @inject...
UsersBase.cs
public class UsersBase : ComponentBase
{
[Inject]
protected UserManager<ApplicationUser>? UserManager { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.