InvalidOperationException:无法解析作用域服务'Microsoft.AspNetCore.Identity.UserManager .NET Core 2.0

时间:2018-04-29 09:37:05

标签: c# asp.net-core asp.net-core-2.0 asp.net-core-mvc-2.0

从.NET Core 1.1升级后遇到此错误

  

InvalidOperationException:无法解析作用域服务   'Microsoft.AspNetCore.Identity.UserManager`1 [Project1.Models.ApplicationUser]'   来自root提供者。   Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(类型   serviceType,ServiceProvider serviceProvider)

     

Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(类型   serviceType,ServiceProvider serviceProvider)   Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(类型   服务类型)   Microsoft.Extensions.Internal.ActivatorUtilities + ConstructorMatcher.CreateInstance(的IServiceProvider   提供商)   Microsoft.Extensions.Internal.ActivatorUtilities.CreateInstance(的IServiceProvider   provider,Type instanceType,Object []参数)   Microsoft.AspNetCore.Builder.UseMiddlewareExtensions + LT;> 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
        }


    }

1 个答案:

答案 0 :(得分:0)

我刚刚将我的应用程序从.NET Core 1.x升级到2.x,并且关于如何从.NET Core 1.x迁移到2.x有一个非常detailed documentation from Microsoft。您需要按照说明进行操作,并确保执行适用于您项目的每个步骤。

例如,我可以告诉您Program.cs与2.X模板创建的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(); } 不同。

ApplicationUser

由于您尚未发布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> { } 的代码,因此我只能发布我的代码。由于我需要将主键从默认字符串更改为GUID,因此我需要为应用程序用户和角色创建自定义类。

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

然后你需要继承AppUser,AppRole和GUID主键的IdentityDbContext。

ConfigureServices

.AddEntityFrameworkStores()来电中,您遗失了.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();

#navbar {
  background: rgb(16, 16, 16);
  color: white;
  width: 70px;
  position: absolute;
  margin: 0;
  top: 0;
  bottom: 0;
  border-right: rgb(246, 246, 255) 1px solid;
}

.collapse-menu-trigger {
  display: block;
  width: 70px;
  height: 50px;
  line-height: 50px;
  text-align: center;
  position: absolute;
  bottom: 0;
  cursor: pointer;
}

.collapse-menu-trigger .material-icons {
  vertical-align: middle;
}

.collapse-menu-trigger .material-icons.icon-def {}