2016-11-15 9 views
2

私は3つのプロジェクト(Web、Console Application、DataAccessLayer)を持つASP.NET Core 1.0ソリューションを持っています。 ASP.NETのコアIDとEntity Frameworkコア(SQL Server - コードファースト)を使用します。コンソール.NETコアアプリケーションでユーザーを作成する

私のコンソールアプリケーション(バックグラウンドタスクで使用)では、ユーザーを作成したいのですが、コンソールアプリケーション(または.NET Core Class Library)でUserManagerオブジェクトにアクセスする方法はありますか?コントローラクラスで

、それは依存性注入と簡単です:

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); 

    //... 
} 

私はコンソールアプリケーションのコアに相当するものを行うことができますどのように?

+0

このためのAPIアクションを作成し、コンソールプログラムから「ユーザー作成Api」を呼び出すことは簡単ではないでしょうか? –

答えて

3

私のコンソールアプリケーション(バックグラウンドタスクで使用)では、ユーザーを作成したいのですが、コンソールアプリケーション(または.NET Coreクラスライブラリ)でUserManagerオブジェクトにアクセスする方法はありますか?

ASP.NETコアと同じです。あなたは自分でブートストラップする必要があります。 Main(コンソールアプリケーションcomposition root - オブジェクトグラフを設定できる最も早い時点)。

ここでServiceCollectionインスタンスを作成し、サービスを登録してコンテナを作成してから、アプリエントリポイントを解決します。そこから、何か他のものが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); 
    } 
} 

あなたが解決する最初のクラスは、すなわちそのA場合は、あなたのUserCreationServiceが、あなたのアプリケーションと限り操作が起こるように生きているアプリケーションを維持する責任の中核であるいくつかのMainApplicationクラス、ではないでしょう(Azure Web Job Hostなど)を実行して、外部からのイベントを(あるメッセージバス経由で)受け取ることができるようにし、各イベントで特定のハンドラまたはアクションを開始します。サービスなど

+0

ありがとうございますTseng :) – orrel

3

Tsengの回答により、このコードが完成しました。場合によっては、誰かが必要とする場合:

public class Program 
    { 
     private interface IUserCreationService 
     { 
      Task CreateUser(); 
     } 

     public static void Main(string[] args) 
     { 
      var services = new ServiceCollection(); 

      services.AddDbContext<ApplicationDbContext>(
      options => 
      { 
       options.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=my-app-db;Trusted_Connection=True;MultipleActiveResultSets=true"); 
      }); 

      // Authentification 
      services.AddIdentity<ApplicationUser, IdentityRole>(opt => 
      { 
       // Configure identity options 
       opt.Password.RequireDigit = false; 
       opt.Password.RequireLowercase = false; 
       opt.Password.RequireUppercase = false; 
       opt.Password.RequireNonAlphanumeric = false; 
       opt.Password.RequiredLength = 6; 
       opt.User.RequireUniqueEmail = true; 
      }) 
       .AddEntityFrameworkStores<ApplicationDbContext>() 
       .AddDefaultTokenProviders(); 

      services.AddScoped<IUserCreationService, UserCreationService>(); 

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

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

      userService.CreateUser().GetAwaiter().GetResult(); 

      Console.ReadKey(); 
     } 

     private class UserCreationService : IUserCreationService 
     { 
      private readonly 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 this.userManager.CreateAsync(user, "123456"); 

       if (result.Succeeded == false) 
       { 
        foreach (var error in result.Errors) 
        { 
         Console.WriteLine(error.Description); 
        } 
       } 
       else 
       { 
        Console.WriteLine("Done."); 
       } 
      } 
     } 
    } 
関連する問題