问题描述
在运行项目时,我遇到了这个问题:
(我使用过 asp.net core 3
。)
When I run the project, I encounter this problem:(I've used asp.net core 3
.)
我该如何解决这个问题?
How can I solve this problem?
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);
}
}
}
}
错误详细信息:
InvalidOperationException:无法解析作用域服务
'Microsoft.AspNetCore.Identity.UserManager`1 [Alpha.Models.Identity .User]'
来自根提供商。
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type
serviceType,IServiceScope scope,IServiceScope rootScope)
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:一个或多个错误发生了。 (无法从根提供商解析
作用域服务
'Microsoft.AspNetCore.Identity.UserManager`1 [Alpha.Models.Identity.User]'
。)
System.Threading。 Tasks.Task.ThrowIfExceptional(bool
includeTaskCanceledExceptions)System.Threading.Tasks.Task.Wait(int
millisecondsTimeout,CancellationToken cancelingToken)
System.Threading.Tasks.Task.Wait()
Alpha.Web.App.Startup.Configure(IApplicationBuilder应用,
IWebHostEnvironment env)在Startup.cs中
+
ApplicationDbContext.CreateAdminAccount(app.ApplicationServices,
配置)。等待(); System.RuntimeMethodHandle.InvokeMethod(对象
目标,object []参数,签名sig,布尔构造函数,布尔
wrapExceptions)System.Reflection.RuntimeMethodInfo.Invoke(对象obj,
BindingFlags invokeAttr,Binder活页夹,object []参数,
CultureInfo文化)
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
构建器)
Microsoft.AspNetCore.Server.IIS.Core.IISServerSetupFilter +<> c__DisplayClass2_0.b__0(IApplicationBuilder
应用程序)
Microsoft.AspNetCore.HostFilteringStartupFilter +<> c__ DisplayClass0_0.b__0(IApplicationBuilder
应用)
Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken
CancellationToken)
Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken
cancelleToken)
Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost
主机,CancellationToken令牌)
Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost
主机, CancellationToken令牌)
Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost
主机)Program.cs
+ $ b中的Alpha.Web.App.Program.Main(string [] args) $ b CreateHostBuilder(args).Build()。Run();
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();
显示原始异常详细信息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
提供者)
Alpha.DataAccess.ApplicationDbC
中的ontext.CreateAdminAccount(IServiceProvider
serviceProvider,IConfiguration配置)
+
UserManager userManager = serviceProvider.GetRequiredService>();
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>();
显示原始异常详细信息System.InvalidOperationException:无法
解析作用域服务
'Microsoft.AspNetCore.Identity.UserManager`1 [Alpha.Models.Identity.User]'
来自根提供商。在
处Microsoft.Extensions.DependencyInjection.ServiceProvider.Microsoft.Extensions.DependencyInjection.ServiceLookup在
处Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type
serviceType,IServiceScope scope,IServiceScope rootScope) .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 $ b b $ b Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService [T](IServiceProvider
prov ider)在
中的
Alpha.DataAccess.ApplicationDbContext.CreateAdminAccount(IServiceProvider
serviceProvider,IConfiguration配置)E:\归档chi项目\Alpha\Alpha.DataAccess\ApplicationDbContext。 cs:line
92 .NET Core 3.0.0 X64 v4.0.0.0 | Microsoft.AspNetCore.Hosting
版本3.0.0-rc2.19465.2 | Microsoft Windows 10.0.17763 |
需要帮助吗?
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?
推荐答案
在包含的屏幕截图中,它表明您在 Startup中获得了以下内容配置
:
From the screenshot you've included, it shows that you've got the following line in Startup.Configure
:
ApplicationDbContext.CreateAdminAccount(app.ApplicationServices, Configuration)
.Wait();
IServiceProvider 实例= https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.aspnetcore.builder.iapplicationbuilder.applicationservices?view=aspnetcore-3.0 rel = noreferrer> IApplicationBuilder。 ApplicationServices
是您的应用程序的 root 服务提供商。错误消息指出,它无法解析 root 服务提供商的作用域服务。
The IServiceProvider
instance stored in IApplicationBuilder.ApplicationServices
is the root service provider for your application. The error message states that it cannot resolve a scoped service from the root service provider.
出现此问题通常,但是针对您的方案最简单的解决方案是将 IServiceProvider
注入您的 Configure
方法并将其传递给 CreateAdminAccount
:
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
:
public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
{
ApplicationDbContext.CreateAdminAccount(serviceProvider, Configuration)
.Wait();
}
IServiceProvider的实例
Configure 的>是 scoped ,这意味着您可以使用它来创建范围服务。
The instance of IServiceProvider
that gets passed into Configure
is scoped, which means that you can use it to create scoped services.
这是完成这项工作所需的全部,但是在 Program
中进行此类播种更为典型。这样可以使关注点与配置管道分离,并且还允许使用 async
/ await
。下面是一个示例:
That's all you need to make this work, but it's more typical to do this type of seeding in Program
. That keeps seeding concerns separate from configuring the pipeline and it also allows the use of 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) =>
// ...
}
您可以解析<$ c $也将 Main
中的c> UserManager< User> 和 RoleManager< Role>
进入 CreateAdminAccount
的用户,而不是使用服务定位器方法的用户。
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.
这篇关于ASP.NET Core 3:无法从根提供程序解析作用域服务'Microsoft.AspNetCore.Identity.UserManager`1 [Alpha.Models.Identity.User]'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!