gpt4 book ai didi

c# - ASP.NET Core 3 : Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager` 1[Alpha. Models.Identity.User]' 来自根提供商

转载 作者:行者123 更新时间:2023-12-05 08:22:47 25 4
gpt4 key购买 nike

我在运行项目的时候遇到了这个问题:(我用过asp.net core 3。)

Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager`1[Alpha.Models.Identity.User]' from root provider.

我该如何解决这个问题?

ApplicationDbContext 类:

public class ApplicationDbContext : IdentityDbContext<User, Role, int, 
UserClaim, UserRole, UserLogin, RoleClaim, UserToken>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{

}
public static async Task CreateAdminAccount(IServiceProvider
serviceProvider, IConfiguration configuration)
{
UserManager<User> userManager =
serviceProvider.GetRequiredService<UserManager<User>>();
RoleManager<Role> roleManager =
serviceProvider.GetRequiredService<RoleManager<Role>>();

string userName = configuration["Data:AdminUser:Name"];
string email = configuration["Data:AdminUser:Email"];
string password = configuration["Data:AdminUser:Password"];
string role = configuration["Data:AdminUser:Role"];

if (await userManager.FindByNameAsync(userName) == null)
{
if (await roleManager.FindByNameAsync(role) == null)
{
await roleManager.CreateAsync(new Role(role));
}

User user = new User
{
Email = email,
UserName = userName
};
var result = userManager.CreateAsync(user, password);
if (result.IsCompletedSuccessfully)
{
await userManager.AddToRoleAsync(user, role);
}
}
}
}

错误详情:

An error occurred while starting the application. AggregateException: One or more errors occurred. (Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager`1[Alpha.Models.Identity.User]' from root provider.) System.Threading.Tasks.Task.ThrowIfExceptional(bool includeTaskCanceledExceptions)

InvalidOperationException: Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager`1[Alpha.Models.Identity.User]' from root provider. Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope)

AggregateException: One or more errors occurred. (Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager`1[Alpha.Models.Identity.User]' from root provider.) System.Threading.Tasks.Task.ThrowIfExceptional(bool includeTaskCanceledExceptions) System.Threading.Tasks.Task.Wait(int millisecondsTimeout, CancellationToken cancellationToken) System.Threading.Tasks.Task.Wait() Alpha.Web.App.Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env) in Startup.cs + ApplicationDbContext.CreateAdminAccount(app.ApplicationServices, Configuration).Wait(); System.RuntimeMethodHandle.InvokeMethod(object target, object[] arguments, Signature sig, bool constructor, bool wrapExceptions) System.Reflection.RuntimeMethodInfo.Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(object instance, IApplicationBuilder builder) Microsoft.AspNetCore.Hosting.ConfigureBuilder+<>c__DisplayClass4_0.b__0(IApplicationBuilder builder) Microsoft.AspNetCore.Hosting.GenericWebHostBuilder+<>c__DisplayClass13_0.b__2(IApplicationBuilder app) Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter+<>c__DisplayClass0_0.g__MiddlewareFilterBuilder|0(IApplicationBuilder builder) Microsoft.AspNetCore.Server.IIS.Core.IISServerSetupFilter+<>c__DisplayClass2_0.b__0(IApplicationBuilder app) Microsoft.AspNetCore.HostFilteringStartupFilter+<>c__DisplayClass0_0.b__0(IApplicationBuilder app) Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken) Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken) Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token) Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token) Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host) Alpha.Web.App.Program.Main(string[] args) in Program.cs + CreateHostBuilder(args).Build().Run();

Show raw exception details InvalidOperationException: Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager`1[Alpha.Models.Identity.User]' from root provider. Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope) Microsoft.Extensions.DependencyInjection.ServiceProvider.Microsoft.Extensions.DependencyInjection.ServiceLookup.IServiceProviderEngineCallback.OnResolve(Type serviceType, IServiceScope scope) Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope) Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType) Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider) Alpha.DataAccess.ApplicationDbContext.CreateAdminAccount(IServiceProvider serviceProvider, IConfiguration configuration) in ApplicationDbContext.cs + UserManager userManager = serviceProvider.GetRequiredService>();

Show raw exception details System.InvalidOperationException: Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager`1[Alpha.Models.Identity.User]' from root provider. at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope) at Microsoft.Extensions.DependencyInjection.ServiceProvider.Microsoft.Extensions.DependencyInjection.ServiceLookup.IServiceProviderEngineCallback.OnResolve(Type serviceType, IServiceScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at Alpha.DataAccess.ApplicationDbContext.CreateAdminAccount(IServiceProvider serviceProvider, IConfiguration configuration) in E:\Archives\Projects\Alpha\Alpha.DataAccess\ApplicationDbContext.cs:line 92 .NET Core 3.0.0 X64 v4.0.0.0 | Microsoft.AspNetCore.Hosting version 3.0.0-rc2.19465.2 | Microsoft Windows 10.0.17763 |
Need help?

error details

最佳答案

从您提供的屏幕截图可以看出,您在 Startup.Configure 中有以下行:

ApplicationDbContext.CreateAdminAccount(app.ApplicationServices, Configuration)
.Wait();

IServiceProvider存储在 IApplicationBuilder.ApplicationServices 中的实例是您应用程序的 服务提供者。错误消息表明它无法解析来自 root 服务提供商的作用域服务。

这个问题经常出现,但最简单的解决方案是注入(inject) IServiceProvider进入你的Configure方法并将其传递给 CreateAdminAccount :

public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
{
ApplicationDbContext.CreateAdminAccount(serviceProvider, Configuration)
.Wait();
}

IServiceProvider 的实例被传递到 Configure作用域,这意味着您可以使用它来创建作用域服务。

这就是完成这项工作所需的全部,但在 Program 中进行此类播种更为典型。 .这使播种问题与配置管道分开,并且还允许使用 async/await .这是一个例子:

public class Program
{
public static async Task Main(string[] args)
{
var host = CreateHostBuilder(args).Build();

using (var scope = host.Services.CreateScope())
{
var serviceProvider = scope.ServiceProvider;
var config = serviceProvider.GetRequiredService<IConfiguration>();

await ApplicationDbContext.CreateAdminAccount(serviceProvider, config);
}

await host.RunAsync();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
// ...
}

你可以解决 UserManager<User>RoleManager<Role>Main也将它们传递给 CreateAdminAccount而不是让它使用服务定位器方法。

关于c# - ASP.NET Core 3 : Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager` 1[Alpha. Models.Identity.User]' 来自根提供商,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58574899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com