Search code examples
.net-coreasp.net-identityblazorusermanager

Create UserManager in Class library


I'm working in a app using Blazor and .NetCore.

I use Microsoft Identity for the roles and Users. In the base project generate by Visual Studio, the code for use identity it's construct by default. For objectives of the project, i'm working with this pattern desing:

Pattern Desing

I need to move the CRUD of Identity to a "Business Class Library". For that i need to create a UserManager and RoleManager, but i don't know to create the UserManager (because the constructor, need 8 parameters)

namespace Business
{
public static class B_Manage
{
    public static void CreateUser()
    {
        using (var IdentityDB = new IDBContext())
        {
            var roleStore = (IRoleStore<IdentityRole>)new RoleStore<IdentityRole>(IdentityDB);
            var roleManager = new RoleManager<IdentityRole>(roleStore, null, null, null, null);

            var userStore = new UserStore<IdentityUser>(IdentityDB);
            var userManager = new UserManager<IdentityUser>()

        }
    }

} 

}

I saw the sample code in others websites, but when i attend to create a new instance, required the others variables.

 public async Task<ActionResult> Index()
    {
        var context = new ApplicationDbContext(); // DefaultConnection
        var store = new UserStore<CustomUser>(context);
        var manager = new UserManager<CustomUser>(store);
     }

Someone have information about i can create a UserManager in a Class Library?


Solution

  • You do not create new UserManager<T> or RoleManager<T>, instead, you need to inject via dependency injection from service collection of the hosted app.

    To inject in your class's constructor you can use below example of UserManager:

    public class SomeClass
    {
        private readonly UserManager<ApplicationUser> _userManager;
    
        public SomeClass(
            UserManager<ApplicationUser> userManager)
        {
            _userManager = userManager;
        }
    
    ...
    

    -or-

    you pass this via parameter to your method.

    public void DoSomething(UserManager<ApplicationUser> userManager)
    {
        ....
    }
    

    Some help you can get from here: