【问题标题】:ASP.Net Core 2.1: No service for type Microsoft.AspNetCore.Identity.UserManagerASP.Net Core 2.1:没有 Microsoft.AspNetCore.Identity.UserManager 类型的服务
【发布时间】:2018-11-18 19:41:07
【问题描述】:

User class:

public class User: IdentityUser
{
}

StartUp.cs:

public class Startup
{
    private readonly IConfiguration _config;

    public Startup(IConfiguration config)
    {
        _config = config;
    }
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddIdentity<User, IdentityRole>(cfg =>
        {
            cfg.User.RequireUniqueEmail = true;
        }).AddEntityFrameworkStores<DutchContext>();

        services.AddDbContext<DutchContext>(cfg =>
        {
            cfg.UseSqlServer("Data Source=.;Initial Catalog=DutchDatabase;Integrated Security=True;MultipleActiveResultSets=true;");
        });

        services.AddAutoMapper();

        services.AddTransient<IMailService, NullMailService>();
        services.AddScoped<IDutchRepository, DutchRepository>();
        services.AddScoped<IAccountRepository, AccountRepository>();
        services.AddScoped<IOrganizationRepository, OrganizationRepostory>();
        services.AddScoped<UserManager<User>, UserManager<User>>();

        services.AddMvc()
            .AddJsonOptions(opt => opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
    {
        //app.UseDefaultFiles();
        if (env.IsDevelopment())
            app.UseDeveloperExceptionPage();
        app.UseStaticFiles();
        app.UseNodeModules(env);
        app.UseAuthentication();
        app.UseMvc(cfg =>
        {
            cfg.MapRoute("Default",
                "{controller}/{action}/{id?}",
                new { controller = "Account", Action = "LogIn" });
        });
        CreateRoles(serviceProvider).Wait();
    }

    private async Task CreateRoles(IServiceProvider serviceProvider)
    {
        //initializing custom roles   
        var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
        var UserManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();
        string[] roleNames = { "Admin", "Tester", "Developer" };
        IdentityResult roleResult;

        foreach (var roleName in roleNames)
        {
            var roleExist = await RoleManager.RoleExistsAsync(roleName);
            if (!roleExist)
            {
                //create the roles and seed them to the database: Question 1  
                roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
            }
        }

        IdentityUser user = await UserManager.FindByEmailAsync("subratkr@gmail.com");

        if (user == null)
        {
            user = new IdentityUser()
            {
                UserName = "admin@gmail.com",
                Email = "admin@gmail.com",
            };
            await UserManager.CreateAsync(user, "Test@123");
        }
        await UserManager.AddToRoleAsync(user, "Admin");

        IdentityUser user1 = await UserManager.FindByEmailAsync("tester@gmail.com");

        if (user1 == null)
        {
            user1 = new IdentityUser()
            {
                UserName = "tester@gmail.com",
                Email = "tester@gmail.com",
            };
            await UserManager.CreateAsync(user1, "Test@123");
        }
        await UserManager.AddToRoleAsync(user1, "Tester");

        IdentityUser user2 = await UserManager.FindByEmailAsync("dev@gmail.com");

        if (user2 == null)
        {
            user2 = new IdentityUser()
            {
                UserName = "dev@gmail.com",
                Email = "dev@gmail.com",
            };
            await UserManager.CreateAsync(user2, "Test@123");
        }
        await UserManager.AddToRoleAsync(user2, "Developer");
    }
}

问题得到异常:

InvalidOperationException:没有服务类型 'Microsoft.AspNetCore.Identity.UserManager.

上线:

var UserManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();

有人可以帮忙吗?谢谢。

【问题讨论】:

    标签: c# asp.net-core asp.net-core-identity


    【解决方案1】:

    使用你的 IdentityUser 实现,用户类

    var UserManager = serviceProvider.GetRequiredService<UserManager<User>>();
    

    因为在 ConfigureServices 方法中,您已经向身份提供者声明使用该类services.AddIdentity&lt;User, IdentityRole&gt;

    【讨论】:

    • 我也在尝试,它显示编译错误:关于数据类型。
    • @SubratGupta 在 DutchContext 类中,你把 User-class 注册为泛型了吗?
    • public class DutchContext : IdentityDbContext 是的,我就是这样做的。即使我能够使用用户类数据使用身份登录注销。但不明白为什么我在这种情况下会出错。
    • var UserManager = serviceProvider.GetRequiredService>();给我类型错误:无法将 MS.AspNetCore.Identity.IndentityUser 转换为 Dutch.Data.User。
    猜你喜欢
    • 2019-01-11
    • 1970-01-01
    • 2018-12-10
    • 2019-03-05
    • 2021-11-01
    • 1970-01-01
    • 2023-01-30
    • 2019-10-29
    • 2019-02-20
    相关资源
    最近更新 更多