Search code examples
asp.net-core-mvcasp.net-identity

How to call a custom identity Register method from a controller in .net core 2.1 mvc


I want to use custom register identity method that is called in a controller to Register users automatically with a corresponding role. Here the code that I found so far:

public class RegisterUsers 
{
private readonly UserManager<ApplicationUser> _userManager;
    public RegisterUsers(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }
    public async Task SystmRegisterUsers(string uname, string sysid, string Email)
    {
         var newuser = new ApplicationUser
        {
            UserName = uname,
            Email = Email,
            SystemuserID = sysid
        };
        string UserPassword = PasswordGenerator.Generate(6, 3, true, true, true, true);
        //var _user = await UserManager.FindByEmailAsync(Configuration.GetSection("UserSettings")["UserEmail"]);
        var createParentUser = await _userManager.CreateAsync(newuser, UserPassword);
        if (createParentUser.Succeeded)
        {
            //here we tie the new user to the "Admin" role 
            await _userManager.AddToRoleAsync(newuser, "Parent");
        }

    }
}

And I want to call the method SystmRegisterUsers like this in a controller

[HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("fullname,id,email,...")]MyModel parent)
        {
           if (ModelState.IsValid)
           {
              //create new records
                _context.Add(parent);
                await _context.SaveChangesAsync();
             // and i want to call the method here to create identity users using the data entered:
                 var instance = new RegisterUsers();
                await instance.SystmRegisterUsers(parent.FullName, parent.Parentid, parent.Parentid);
           }
                 return View(parent);
    }

And it is saying I’m missing an argument that is corresponds to userManager . I don’t even know if it is the right way to do what I want to do, I think I’m missing some basic thing please help!


Solution

  • For RegisterUsers, it needs UserManager<ApplicationUser> userManager, for resolving the RegisterUsers from Dependency Injection, you could follow steps below:

    • Register RegisterUsers in Startup.cs

              public void ConfigureServices(IServiceCollection services)
          {
              //your rest code
      
              services.AddScoped<RegisterUsers>();
          }
      
    • Initialize RegisterUsers by Dependency Injection

          public class HomeController : Controller
      {
          private readonly RegisterUsers _registerUsers;
          public HomeController(RegisterUsers registerUsers)
          {
              _registerUsers = registerUsers;
          }            
      
          public async Task<IActionResult> Index()
          {
              await _registerUsers.SystmRegisterUsers("a1", "b1", "c1");
              return View();
          }