简体   繁体   中英

InvalidOperationException: Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager .NET Core 2.0

Encountering this error after upgrading from .NET Core 1.1

InvalidOperationException: Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager`1[Project1.Models.ApplicationUser]' from root provider. Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, ServiceProvider serviceProvider)

Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, ServiceProvider serviceProvider) Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType) Microsoft.Extensions.Internal.ActivatorUtilities+ConstructorMatcher.CreateInstance(IServiceProvider provider) Microsoft.Extensions.Internal.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters) Microsoft.AspNetCore.Builder.UseMiddlewareExtensions+<>c__DisplayClass4_0.b__0(RequestDelegate next) Microsoft.AspNetCore.Builder.Internal.ApplicationBuilder.Build() Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()

Startup.cs

public void ConfigureServices(IServiceCollection services) {

services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("connstring")));

            services.AddIdentity<ApplicationUser, IdentityRole>(o => {
                // configure identity options
                o.Password.RequireDigit = false;
                o.Password.RequireLowercase = false;
                o.Password.RequireUppercase = false;
                o.Password.RequireNonAlphanumeric = false;
                o.Password.RequiredLength = 6;
            })


  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
            app.UseAuthentication();
        app.UseForwardedHeaders(new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
        });

        var rewriteOptions = new RewriteOptions().AddRedirectToHttps();
        app.UseRewriter(rewriteOptions);

Program.cs

public class Program
    {
        public static void Main(string[] args)
        {
            var host = BuildWebHost(args);

            host.Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
             .UseSetting("detailedErrors", "true")
             .UseStartup<Startup>()
            .Build();
    }

ApplicationDBContext

public class ApplicationDbContext : IdentityDbContext<ApplicationUser> {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options) {
        }


        public DbSet<UserDevice> UserDevices { get; set; }
        public DbSet<Advertisement> Advertisements { get; set; }


        protected override void OnModelCreating(ModelBuilder builder) {
            base.OnModelCreating(builder);

            builder.Entity<UserDevice>().HasKey(x => new { x.Id, x.DeviceId }); // configure composite key
        }


    }

I just upgraded my application from .NET Core 1.x to 2.x and there is a very detailed documentation from Microsoft on how to migration from .NET Core 1.x to 2.x. You need to follow the instructions and make sure you do every step applicable to your project.

For example, I can tell your Program.cs is different from the one created by 2.X template.

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>

        // You don't need .UseKestrel() and others as they're from 1.X.
        // .CreateDefaultBuilder() already includes them.

        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

Since you haven't posted the code for ApplicationUser , I can only post mine. Since I need to change the primary key from the default string to GUID, I need to create custom classes for application user and roles.

public class AppUser : IdentityUser<Guid>
{
    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }

    public string DisplayName => $"{ this.FirstName } { this.LastName }";
}

public class AppRole : IdentityRole<Guid>
{
}

Then you need to inherit from the IdentityDbContext of AppUser, AppRole and the GUID primary key.

public class AppIdentityDbContext : IdentityDbContext<AppUser, AppRole, Guid>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<AppUser>().ToTable("User");
        builder.Entity<AppRole>().ToTable("Role");

        builder.Entity<IdentityUserRole<Guid>>().ToTable("UserRole");
        builder.Entity<IdentityUserClaim<Guid>>().ToTable("UserClaim");
        builder.Entity<IdentityRoleClaim<Guid>>().ToTable("RoleClaim");
        builder.Entity<IdentityUserLogin<Guid>>().ToTable("UserLogin");
        builder.Entity<IdentityUserToken<Guid>>().ToTable("UserToken");
    }
}

In the ConfigureServices call, you're missing .AddEntityFrameworkStores() and .AddDefaultTokenProviders() .

services.AddIdentity<AppUser, AppRole>(o => {
    // configure identity options
    o.Password.RequireDigit = false;
    o.Password.RequireLowercase = false;
    o.Password.RequireUppercase = false;
    o.Password.RequireNonAlphanumeric = false;
    o.Password.RequiredLength = 6;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
// Components that generate the confirm email and reset password tokens
.AddDefaultTokenProviders();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM