无法获取 UserManager class
Cannot get the UserManager class
我想做的是添加一个新的管理员用户并为其分配管理员角色。
所以..我去了Configure
方法中的Startup.cs
class,写了下面的代码:
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);
但是,我收到以下错误消息:
Severity Code Description Project File Line Suppression State
Error CS7036 There is no argument given that corresponds to the
required formal parameter 'optionsAccessor' of
UserManager.UserManager(IUserStore,
IOptions, IPasswordHasher,
IEnumerable>,
IEnumerable>, ILookupNormalizer,
IdentityErrorDescriber, IServiceProvider,
ILogger>)' FinalProject..NETCoreApp,Version=v1.0 C:\Users\Or
Natan\Documents\Visual Studio
2015\Projects\FinalProject\src\FinalProject\Startup.cs 101 Active
这个错误让我很难受。显然我需要 userManager 才能创建新用户,但我无法初始化它。
您可以使用dependency injection 获取UserManager 的实例。只需在配置方法中添加一个参数,像这样:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
然后您可以创建用户和角色。我通常将此代码移动到静态 class...
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 = "info@example.com", Email = "info@example.com" }, "p@ssw0rd");
}
// Ensure admin privileges
ApplicationUser admin = await userManager.FindByEmailAsync("info@example.com");
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();
}
在 Entity Framework Core database seeding will be added as a feature 的下一个版本中。
正如@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 = "info@example.com", Email = "info@example.com" },
"P@ssw0rd").Result;
}
}
}
和 Startup
class 和 Configure
方法:
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);
}
}
我想做的是添加一个新的管理员用户并为其分配管理员角色。
所以..我去了Configure
方法中的Startup.cs
class,写了下面的代码:
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);
但是,我收到以下错误消息:
Severity Code Description Project File Line Suppression State Error CS7036 There is no argument given that corresponds to the required formal parameter 'optionsAccessor' of UserManager.UserManager(IUserStore, IOptions, IPasswordHasher, IEnumerable>, IEnumerable>, ILookupNormalizer, IdentityErrorDescriber, IServiceProvider, ILogger>)' FinalProject..NETCoreApp,Version=v1.0 C:\Users\Or Natan\Documents\Visual Studio 2015\Projects\FinalProject\src\FinalProject\Startup.cs 101 Active
这个错误让我很难受。显然我需要 userManager 才能创建新用户,但我无法初始化它。
您可以使用dependency injection 获取UserManager 的实例。只需在配置方法中添加一个参数,像这样:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
然后您可以创建用户和角色。我通常将此代码移动到静态 class...
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 = "info@example.com", Email = "info@example.com" }, "p@ssw0rd");
}
// Ensure admin privileges
ApplicationUser admin = await userManager.FindByEmailAsync("info@example.com");
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();
}
在 Entity Framework Core database seeding will be added as a feature 的下一个版本中。
正如@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 = "info@example.com", Email = "info@example.com" },
"P@ssw0rd").Result;
}
}
}
和 Startup
class 和 Configure
方法:
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);
}
}