Joel Mason
Joel Mason

Reputation: 43

How do I properly use dependency injection to include asp.net core identity UserManager on a Blazor component?

How do I properly use dependency injection to include asp.net core identity UserManager on a Blazor component?

I scaffolded Identity into the project, created a custom field, and edited the Identity pages for displaying and editing this field during registration and profile pages.

Being that those pages are mainly for the logged in user, I need to build a page for an admin to view and edit users.

I created a Blazor page and copied from "Index.cshtml.cs" this code which appears all over the internet as well:

    private readonly UserManager<ApplicationUser> _userManager;
    private readonly SignInManager<ApplicationUser> _signInManager;

    public IndexModel(
        UserManager<ApplicationUser> userManager,
        SignInManager<ApplicationUser> signInManager)
    {
        _userManager = userManager;
        _signInManager = signInManager;
    }

I used the guide here: Micosoft Docs, to create a Razor Component to specify a base class for the component. Being that it is a server side Blazor app, I am thinking that this should be fine, but it is not.

My class code is:

namespace UsersComponent
{
public class UsersBase : ComponentBase
{
    private readonly UserManager<ApplicationUser> _userManager;

    public UsersBase(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

I am getting this error on the dependency injection of:

    public UsersBase(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

The error is this:

CS7036  There is no argument given that corresponds to the required formal parameter 'userManager' of 'UsersBase.UsersBase(UserManager<ApplicationUser>)'

Can anyone point me towards alleviating this error? I would greatly appreciate it.

Upvotes: 2

Views: 1285

Answers (1)

Brian Parker
Brian Parker

Reputation: 14553

I am assuming you are using something like the following in Program.cs : builder.Services.AddDefaultIdentity<ApplicationUser>...

For injection in razor components your need to use the [Inject] attribute on a property or @inject ... in the razor markup area.

UsersBase.cs

public class UsersBase : ComponentBase
{
    [Inject] 
    protected UserManager<ApplicationUser>? UserManager { get; set; }
}

Upvotes: 3

Related Questions