我正在尝试基于http://docs.identityserver.io/en/latest/quickstarts/8_aspnet_identity.html并使用https://github.com/IdentityServer/IdentityServer4/tree/master/samples/Quickstarts/8_AspNetIdentity中的代码作为模板来启动Identity Server实例,但是我无法获取种子数据。
每个示例应用程序都有我的program.cs和startup.cs。当我打电话
var userMgr = scope.ServiceProvider.GetRequiredService<UserManager<IdentityUser>>();
从SeedData.EnsureSeedData
方法开始,
var services = new ServiceCollection();
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString));
services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
using var serviceProvider = services.BuildServiceProvider();
using var scope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope();
var context = scope.ServiceProvider.GetService<ApplicationDbContext>();
context.Database.Migrate();
var userMgr = scope.ServiceProvider.GetRequiredService<UserManager<IdentityUser>>();
我收到以下错误。
Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger`1[Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]]' while attempting to activate 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]'.
如何为ILogger<UserManager<IdentityUser>>>
注册服务?
我觉得我缺少明显的东西,但看不到它是什么。
答案 0 :(得分:2)
这是我使用用户管理器播种数据的方式
public static void Main(string[] args)
{
try
{
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
SeedData.Initialize(services).Wait();
}
host.Run();
}
}
在种子数据类中
private static async Task SeedUser(User user, ApplicationDbContext context, IServiceProvider serviceProvider,
string[] roles)
{
var password = new PasswordHasher<User>();
var hashed = password.HashPassword(user, "123456");
user.PasswordHash = hashed;
var userStore = new UserStore<User>(context);
await userStore.CreateAsync(user);
await EnsureRole(serviceProvider, user.Email, roles);
await context.SaveChangesAsync();
}
您可以查看我的完整代码here
让我知道您是否需要任何帮助。