如何在项目中使用多个IdentityDbContext <t>?

时间:2018-12-16 16:29:09

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

我创建了两个IdentityDbContext,一个是AdminIdentityDbContext:IdentityDbContext,另一个是StudentIdentityDbContext:IdentityDbContext。

我创建了两个控制器,一个是:

    public class AdminAccountController : Controller
    {
        private UserManager<Admin> _userManager;
        private SignInManager<Admin> _signInManager;

        public AdminAccountController(UserManager<Admin> userManager, SignInManager<Admin> signInManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
        }
Another is:

public class StudentAccountController : Controller
   {
       private UserManager<Student> _userManager;
       private SignInManager<Student> _signInManager;

       public StudentAccountController(UserManager<Student> studentManager, SignInManager<Student> signInManager)
       {
           _userManager = studentManager;
           _signInManager = signInManager;
       }

我的Startup.cs如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LibraryDemo.Data;
using LibraryDemo.Infrastructure;
using LibraryDemo.Models.DomainModels;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace LibraryDemo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddDbContext<LendingInfoDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("LendingInfoDbContext"));
            });
            services.AddDbContext<AdminIdentityDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("AdminIdentityDbContext"));
            });
            services.AddDbContext<StudentIdentityDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("StudentIdentityDbContext"));
            });
            services.AddIdentity<Student, IdentityRole>(opts =>
                {
                    opts.User.RequireUniqueEmail = true;
                    opts.User.AllowedUserNameCharacters = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789";
                    opts.Password.RequiredLength = 6;
                    opts.Password.RequireNonAlphanumeric = false;
                    opts.Password.RequireLowercase = false;
                    opts.Password.RequireUppercase = false;
                    opts.Password.RequireDigit = false;
                }).AddEntityFrameworkStores<StudentIdentityDbContext>()
                .AddDefaultTokenProviders();
            services.ConfigureApplicationCookie(opts =>
            {
                opts.LoginPath = "/StudentAccount/Login";
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
            DatabaseInitiator.Initial(app.ApplicationServices).Wait();
        }
    }
}

但是当我获得站点“ / AdminAccount / Login”时,出现了错误:

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[LibraryDemo.Models.DomainModels.Admin]' while attempting to activate 'LibraryDemo.Controllers.AdminAccountController'.

我不喜欢“角色”功能,那么我还能做些什么来解决此问题?非常感谢。

我试图更改DbContext的架构,但失败了。

其他上下文 我把项目放到了github: https://github.com/NanaseRuri/LibraryDemo

1 个答案:

答案 0 :(得分:1)

您的问题不是由您的两个数据库上下文引起的,这是由于您设置身份中间件的方式引起的。

您正在使用StudentIdentityRole类来设置身份中间件。这意味着UserManager是通过Student类设置的,因此没有UserManager<Admin>类的Admin的实例。

根据您的结构,您似乎需要两个角色:一个是学生,另一个是管理员。这样,您可以保留一个用户管理器。