Reputation: 194
I am trying to spin up an Identity Server instance, based on http://docs.identityserver.io/en/latest/quickstarts/8_aspnet_identity.html and using the code from https://github.com/IdentityServer/IdentityServer4/tree/master/samples/Quickstarts/8_AspNetIdentity as my template but I am having trouble getting the seed data happening.
I have my program.cs and startup.cs as per the sample application. When I call
var userMgr = scope.ServiceProvider.GetRequiredService<UserManager<IdentityUser>>();
from the SeedData.EnsureSeedData
method, which comes after
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>>();
I get the following error.
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]'.
How do I register services for ILogger<UserManager<IdentityUser>>>
?
I feel like I am missing something obvious but can't see what it is.
Upvotes: 2
Views: 604
Reputation: 20102
Here is how I seed data using user manager
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();
}
}
And in seed data class
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();
}
You can view my full code here
Let me know if you need any help.
Upvotes: 2