[英]ASP.NET Core 3: Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager`1[Alpha.Models.Identity.User]' from root provider
When I run the project, I encounter this problem: (I've used asp.net core 3
.)运行项目时,遇到这个问题:(我用过
asp.net core 3
。)
Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager`1[Alpha.Models.Identity.User]' from root provider.
无法从根提供程序解析范围服务“Microsoft.AspNetCore.Identity.UserManager`1[Alpha.Models.Identity.User]”。
How can I solve this problem?我怎么解决这个问题?
ApplicationDbContext class: ApplicationDbContext class:
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);
}
}
}
}
Details of error:错误详情:
An error occurred while starting the application.
启动应用程序时发生错误。 AggregateException: One or more errors occurred.
AggregateException:发生一个或多个错误。 (Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager`1[Alpha.Models.Identity.User]' from root provider.) System.Threading.Tasks.Task.ThrowIfExceptional(bool includeTaskCanceledExceptions)
(无法从根提供程序解析范围服务“Microsoft.AspNetCore.Identity.UserManager`1[Alpha.Models.Identity.User]”。) System.Threading.Tasks.Task.ThrowIfExceptional(bool includeTaskCanceledExceptions)
InvalidOperationException: Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager`1[Alpha.Models.Identity.User]' from root provider.
InvalidOperationException:无法从根提供程序解析范围服务“Microsoft.AspNetCore.Identity.UserManager`1[Alpha.Models.Identity.User]”。 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(类型 serviceType,IServiceScope scope,IServiceScope rootScope)
AggregateException: One or more errors occurred.
AggregateException:发生一个或多个错误。 (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();
(无法从根提供程序解析范围服务“Microsoft.AspNetCore.Identity.UserManager`1[Alpha.Models.Identity.User]”。) System.Threading.Tasks.Task.ThrowIfExceptional(bool includeTaskCanceledExceptions) System.Threading.Tasks.Task Startup.cs + ApplicationDbContext.CreateAdminAccount(app.ApplicationServices, Configuration) 中的 .Wait(int millisecondsTimeout, CancellationToken cancelToken) System.Threading.Tasks.Task.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.AspNetCo
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, CultureInfoculture) Microsoft。 AspNetCore.Hosting.ConfigureBuilder.Invoke(对象实例,IApplicationBuilder 构建器)Microsoft.AspNetCore.Hosting.ConfigureBuilder+<>c__DisplayClass4_0.b__0(IApplicationBuilder 构建器)Microsoft.AspNetCore.Hosting.GenericWebHostBuilder+<>c__DisplayClass13_0.b__2(IApplicationBuilder 应用程序)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+(IcApplicationBuilder app)0_0.StartupFilter+(IcApplicationBuilder app)0_0.StartupFilter+微软.AspNetCo re.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();
re.Hosting.GenericWebHostService.StartAsync(CancellationToken cancelToken) Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancelToken) Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token) Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions。 RunAsync(IHost 主机,CancellationToken 令牌)Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost 主机)Alpha.Web.App.Program.Main(string[] args) 在 Program.cs + CreateHostBuilder(args).Build()。跑();
Show raw exception details InvalidOperationException: Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager`1[Alpha.Models.Identity.User]' from root provider.
显示原始异常详细信息 InvalidOperationException:无法从根提供程序解析范围服务“Microsoft.AspNetCore.Identity.UserManager`1[Alpha.Models.Identity.User]”。 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, IC
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(类型 serviceType,IServiceScope scope,IServiceScope rootScope)Microsoft.Extensions.DependencyInjection.ServiceProvider.Microsoft.Extensions.DependencyInjection.ServiceLookup.IServiceProviderEngineCallback.OnResolve(类型 serviceType,IServiceScope 范围)Microsoft。 .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, IC onfiguration configuration) in ApplicationDbContext.cs + UserManager userManager = serviceProvider.GetRequiredService>();
onfiguration 配置)在 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.
显示原始异常详细信息 System.InvalidOperationException:无法从根提供商解析范围服务“Microsoft.AspNetCore.Identity.UserManager`1[Alpha.Models.Identity.User]”。 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)
在 Microsoft.Extensions.DependencyInjection.ServiceProvider.Microsoft.Extensions.DependencyInjection.ServiceLookup.IServiceProviderEngineCallback.OnResolve(键入 serviceType,IServiceScope scope,IServiceScope rootScope)处的 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(键入 serviceType,IServiceScope 范围) Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(类型 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.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType) 在 Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) 在 Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)在 E:\Archives\Projects\Alpha\Alpha.DataAccess\ApplicationDbContext.cs:line 92 .NET Core 3.0.0 X64 v4.0.0.0 中的 Alpha.DataAccess.ApplicationDbContext.CreateAdminAccount(IServiceProvider serviceProvider, IConfiguration 配置) | Microsoft.AspNetCore.Hosting version 3.0.0-rc2.19465.2 |
Microsoft.AspNetCore.Hosting 版本 3.0.0-rc2.19465.2 | Microsoft Windows 10.0.17763 |
微软 Windows 10.0.17763 |
Need help?需要帮忙?
From the screenshot you've included, it shows that you've got the following line in Startup.Configure
:从您包含的屏幕截图中,它表明您在
Startup.Configure
中有以下行:
ApplicationDbContext.CreateAdminAccount(app.ApplicationServices, Configuration)
.Wait();
The IServiceProvider
instance stored in IApplicationBuilder.ApplicationServices
is the root service provider for your application.存储在
IApplicationBuilder.ApplicationServices
中的IServiceProvider
实例是应用程序的根服务提供者。 The error message states that it cannot resolve a scoped service from the root service provider.错误消息指出它无法从根服务提供商解析范围服务。
This issue comes up often, but the easiest solution for your scenario is to inject IServiceProvider
into your Configure
method and pass that into CreateAdminAccount
:这个问题经常出现,但最简单的解决方案是将
IServiceProvider
注入您的Configure
方法并将其传递给CreateAdminAccount
:
public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
{
ApplicationDbContext.CreateAdminAccount(serviceProvider, Configuration)
.Wait();
}
The instance of IServiceProvider
that gets passed into Configure
is scoped , which means that you can use it to create scoped services.传递给
Configure
的IServiceProvider
实例是scoped ,这意味着您可以使用它来创建范围服务。
That's all you need to make this work, but it's more typical to do this type of seeding in Program
.这就是完成这项工作所需的全部内容,但在
Program
中进行这种类型的播种更为典型。 That keeps seeding concerns separate from configuring the pipeline and it also allows the use of async
/ await
.这使播种问题与配置管道分开,并且还允许使用
async
/ await
。 Here's an example:这是一个例子:
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) =>
// ...
}
You could resolve UserManager<User>
and RoleManager<Role>
in Main
too, and pass those in to CreateAdminAccount
rather than having it use the service-locator approach.您也可以在
Main
中解析UserManager<User>
和RoleManager<Role>
,并将它们传递给CreateAdminAccount
而不是让它使用服务定位器方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.