2016-10-13 2 views
2

내가하려는 것은 새 관리 사용자를 추가하고이를 관리 역할에 할당하는 것입니다. 그래서 .. 나는 Configure 방법에 Startup.cs 클래스에 가서 다음 코드를 작성 : 그러나UserManager 클래스를 가져올 수 없습니다.

var context = app.ApplicationServices.GetService<ApplicationDbContext>(); 

// Getting required parameters in order to get the user manager 
var userStore = new UserStore<ApplicationUser>(context); 

// Finally! get the user manager! 
var userManager = new UserManager<ApplicationUser>(userStore); 

을, 나는 다음과 같은 오류 메시지가 얻을 :

심각도 코드 설명 프로젝트 파일 라인 억제 상태 을 오류 CS7036 의 형식 매개 변수 'optionsAccessor'에 해당하는 인수가 없습니다. UserManager.UserManager (IUserStore, IOptions, IPasswordHasher, IEnumera 상상력>, 을 IEnumerable>, ILookupNormalizer, IdentityErrorDescriber, IServiceProvider, 하는 ILogger>) 'FinalProject..NETCoreApp, 버전 = 1.0 버전 C : \ 사용자 \ 또는 나탄 \ 문서는 \ Visual Studio를 2015 \ 프로젝트 \ FinalProject \ SRC \ FinalProject \ Startup.cs 101 Active

이 오류는 나를 죽이고 있습니다. 분명히 새 사용자를 만들려면 userManager가 필요하지만이 작업은 초기화 할 수 없습니다.

+0

은 일반적으로 사람들이 DBContext과 그 직접 수행 또는 어쩌면 당신이 할 수있는 시작의 데이터를 시드 먼저이 같은 확장 방법을 만들 데이터베이스를 시드 UserStore와 함께. Google에서 EF Core를 사용하여 데이터를 시드하는 방법에 대해 알아보고 뮤직 스토어 앱 등을 볼 수 있습니다. 내 프로젝트에 관심이있을 수 있습니다.이 프로젝트는 신원 사용자 및 역할 및 소유권 관리를위한 UI를 제공하며 시작시 https : // github. com/joeaudette/cloudscribe –

답변

4

dependency injection을 사용하여 UserManager의 인스턴스를 얻을 수 있습니다. 다음과 같이 configure 메소드에 매개 변수를 추가하십시오.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager) 

그런 다음 사용자 및 역할을 작성할 수 있습니다. 나는 보통 ... 정적 클래스에이 코드를 이동

public static class DbInitializer 
{ 
    public static async Task Initialize(ApplicationDbContext context, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager) 
    { 
     // Ensure that the database exists and all pending migrations are applied. 
     context.Database.Migrate(); 

     // Create roles 
     string[] roles = new string[] { "UserManager", "StaffManager" }; 
     foreach (string role in roles) 
     { 
      if (!await roleManager.RoleExistsAsync(role)) 
      { 
       await roleManager.CreateAsync(new IdentityRole(role)); 
      } 
     } 

     // Create admin user 
     if (!context.Users.Any()) 
     { 
      await userManager.CreateAsync(new ApplicationUser() { UserName = "[email protected]", Email = "[email protected]" }, "[email protected]"); 
     } 

     // Ensure admin privileges 
     ApplicationUser admin = await userManager.FindByEmailAsync("[email protected]"); 
     foreach (string role in roles) 
     { 
      await userManager.AddToRoleAsync(admin, role); 
     } 
    } 
} 

... 그리고 Startup.Configure 방법에서 메서드를 호출 : 엔티티 프레임 워크 코어의 다음 릴리스 중 하나에서

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager) 
{ 
    // Code omitted for brevity 

    // Create seed data 
    DbInitializer.Initialize(context, userManager, roleManager).Wait(); 
} 

database seeding will be added as a feature.

+0

고맙습니다. 결국 다른 방법을 찾았습니다. –

+0

// 응용 프로그램의 db 컨텍스트를 가져옵니다. var context = app.ApplicationServices.GetService (); // 사용자 관리자 가져 오기 var userManager = app.ApplicationServices.GetService >(); // 역할 관리자 가져 오기 var roleManager = app.ApplicationServices.GetService >(); 간단히 app 매개 변수를 사용하여 필요한 서비스를 얻을 수 있습니다. –

0

마찬가지로 @JuliusHardt는 종속성 주입을 통해 UserManager의 인스턴스를 얻을 수 있다고 말했습니다.

public static class ApplicationDbContextExtensions 
{ 
    public static void EnsureSeedData(this ApplicationDbContext context, UserManager<ApplicationUser> userManager) 
    { 
     if (!context.Users.Any()) 
     { 
      var result = userManager.CreateAsync(
       new ApplicationUser { UserName = "[email protected]", Email = "[email protected]" }, 
       "[email protected]").Result; 
     } 
    } 
} 

수업 StartupConfigure 방법 :

if (env.IsDevelopment()) 
{ 
    app.UseDeveloperExceptionPage(); 
    app.UseDatabaseErrorPage(); 
    app.UseBrowserLink(); 
    using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope()) 
    { 
     // First apply pendding migrations if exist 
     serviceScope.ServiceProvider.GetService<ApplicationDbContext>().Database.Migrate(); 

     // Then call seeder method 
     var userManager = serviceScope.ServiceProvider.GetService<UserManager<ApplicationUser>>(); 
     serviceScope.ServiceProvider.GetService<ApplicationDbContext>().EnsureSeedData(userManager); 
    } 
} 
관련 문제