Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

c# - 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.)

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

How can I solve this problem?

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. (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:ArchivesProjectsAlphaAlpha.DataAccessApplicationDbContext.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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the screenshot you've included, it shows that you've got the following line in Startup.Configure:

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

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.

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

The instance of IServiceProvider that gets passed into Configure is scoped, which means that you can use it to create scoped services.

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) =>
        // ...
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...