Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an User in a Console .NET Core Application

I have a ASP.NET Core 1.0 Solution with 3 projects (Web, Console Application, DataAccessLayer). I use ASP.NET Core Identity and Entity Framework Core (SQL Server - Code First).

In my Console Application (Used for background tasks), I want to create users, but how I can have access to UserManager object in a Console Application (Or in a .NET Core Class Library) ?

In a controller class, it's easy with Dependency Injection :

public class AccountController : Controller  {
private readonly UserManager<ApplicationUser> _userManager;

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

//...

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model)
{
    var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
    var result = await _userManager.CreateAsync(user, model.Password);

    //...
}

How I can do the equivalent in a Console Core Application ?

like image 675
orrel Avatar asked Nov 15 '16 09:11

orrel


People also ask

How do I create a user console?

In the Configuration > User Management > Console Users tab, click the Create User button. In the Add Console User dialog box that opens, enter the required name for the new Console User. Enter a local ObserveIT user, or select an Active Directory domain for authentication. Enter a password, and confirm the password.

Which .NET CLI command creates a new console application?

The dotnet new command creates a . NET project or other artifacts based on a template. The command calls the template engine to create the artifacts on disk based on the specified template and options.


1 Answers

In my Console Application (Used for background tasks), I want to create users, but how I can have access to UserManager object in a Console Application (Or in a .NET Core Class Library) ?

Same as you do it in ASP.NET Core. You just need to bootstrap it yourself. Inside your Main (which is the console applications composition root - the earliest point where you can set up your object graph).

Here you create a ServiceCollection instance, register the services and build the container, then resolve your app entry point. From there, anything else goes via DI.

public static int Main(string[] args)
{
    var services = new ServiceCollection();
    // You can use the same `AddXxx` methods you did in ASP.NET Core
    services.AddIdentity();
    // Or register manually
    services.AddTransient<IMyService,MyService();
    services.AddScoped<IUserCreationService,UserCreationService>();
    ...

    // build the IoC from the service collection
    var provider = services.BuildServiceProvider();

    var userService = provider.GetService<IUserCreationService>();

    // we can't await async in Main method, so here this is okay
    userService.CreateUser().GetAwaiter().GetResult();
}

public class UserCreationService : IUserCreationService 
{
    public UserManager<ApplicationUser> userManager;

    public UserCreationService(UserManager<ApplicationUser> userManager)
    {
        this.userManager = userManager;
    } 

    public async Task CreateUser() 
    {
        var user = new ApplicationUser { UserName = "TestUser", Email = "[email protected]" };
        var result = await _userManager.CreateAsync(user, model.Password);
    }
}

In practice the first class you resolve wouldn't be your UserCreationService but some MainApplication class, which is the core of your application and responsible for keeping the application alive as long as the operation happens, i.e. if its a background worker you run some kind of host (Azure Web Job Host etc.) which keeps the application running so it can receive events from outside (via some message bus) and on each event starts a specific handler or action, which in turn resolves other services etc.

like image 159
Tseng Avatar answered Oct 23 '22 04:10

Tseng