簡體   English   中英

aspnet.core 使用 UserManager 播種數據<identityuser></identityuser>

[英]aspnet.core Seeding data using UserManager<IdentityUser>

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作為我的模板,但我無法獲取種子數據。

根據示例應用程序,我有我的 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>>>注冊服務?

我覺得我錯過了一些明顯的東西,但看不到它是什么。

這是我使用用戶管理器播種數據的方式

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

並在種子數據 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();
        }

你可以在這里查看我的完整代碼

如果您需要任何幫助,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM