【问题标题】:How can I change the dbContext of userManager in ASP.NET Core?如何在 ASP.NET Core 中更改 userManager 的 dbContext?
【发布时间】:2020-12-17 18:00:15
【问题描述】:

我有两个数据库。

  • application_db
  • registry_db

application_db 用于应用程序获得工作并使用 ApplicationDbContext

registry_db 用于管理所有帐户。我想首先在我的注册表服务上创建一个帐户,然后将创建的帐户(信息较少)插入 application db。 Registry_db 正在使用 RegistryDbContext

我已经通过依赖注入成功地在我的注册表服务中注入了两个上下文(ApplicationDbContext 和 RegistryDbContext)。

我的启动如下所示:

services.AddCors();
services
.AddDbContext<RegistryDbContext>(
        options => options
        .UseNpgsql(
            Configuration.GetConnectionString("DefaultConnection"),
            b => b.MigrationsAssembly("Codeflow.Registry")
        )
    );

services
    .AddDbContext<ApplicationDbContext>(
    options => options
    .UseNpgsql(
            Configuration.GetConnectionString("ProductionConnection"),
        b => b.MigrationsAssembly("Codeflow.Registry")
    )
);

在我的注册表服务中,我可以通过依赖注入获取 userManager 并创建一个帐户。默认情况下,userManager 使用 RegistryDbContext。通过注册表服务成功创建帐户后,我想在 application_db 中(通过 ApplicationDbContext)创建相同的帐户。但是我卡在这行代码中

// first I am creating the account in registry_db
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{ 
    // once the account is created, I would like to create the account on application_db     
    // here I am getting the dbContext for the application_db
    // I can get it also over the dependency injection if needed
    using (ApplicationDbContext dbCtx = new ApplicationDbContext())
    {
         // Here I am getting the Error. The context is ok, but an error appeard with ApplicationUser.
         var test = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(dbCtx));
    }
}

我收到此错误消息:

错误:没有给出与所需参数相对应的参数 格式参数 '用户管理器'的'optionsAccessor'。用户管理器(IUserStore,IOptions, IPasswordHasher, IEnumerable>, IEnumerable>,ILookupNormalizer, IdentityErrorDescriber, IServiceProbider, ILogger>)'

我的 ApplicationUser 类如下所示:

public class ApplicationUser : IdentityUser<Guid>
{
    public Guid GenderId { get; set; }
    [ForeignKey("GenderId")]
    public Gender Gender { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime BirthDay { get; set; }
}

出了什么问题或遗漏了什么? 我已经尝试关注此帖子here,但没有运气。是否有其他方法可以创建具有其他上下文的 userManager 实例?

【问题讨论】:

  • UserManager 构造函数有很多参数,而您只指定了用户存储。您可以尝试为其他参数指定 null。
  • var test = new UserManager(new UserStore, null, null, null, null, null, null, null, null);现在我收到此消息:类型“ApplicationUser”不能用作泛型类型或方法“UserStore”中的类型“TUser”。没有从 'ApplicationUser' 到 'Microsoft.AspNertCore.Identity.IdentityUser. 的 implocot 引用转换

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


【解决方案1】:

这是对构造函数的依赖注入。使用 DI,您不应该直接初始化您的服务。你应该在Startup.cs注册你的Service和ApplicationContext。

当你需要你的 Service 时,你应该通过构造函数将它注入到控制器中,DI 链会自动将 ApplicationContext 的实例注入到 Service 中。

当然,如果您不需要为控制器中的每个方法提供服务,您可以将其初始化为方法:

[Route("api/[controller]")]
public class MyController : Controller
{
    [HttpGet]
    public async IEnumerable<object> Get([FromServices] ApplicationContext context,
                                         MyType myMainParam)
    {
        ...
    }
}

但是您真正需要做的是实现您自己的UserManagerFactory 版本,this link 可能会有所帮助。

this post 也可能有帮助。

附注:

this 线程中查看@Singularity222 的答案。他在his repo 中做了你想做的同样的事情。

还有this thread owner of Identity project (!) 表示您需要实现自己的UserStore 版本。

【讨论】:

  • 我认为您没有理解我帖子中的问题。注入 dbContext 没有问题。我唯一的问题是我无法创建具有不同上下文的 userManager。 var test = new UserManager(new UserStore, null, null, null, null, null, null, null, null);给出此错误消息:类型“ApplicationUser”不能用作泛型类型或方法“UserStore”中的类型“TUser”。没有从 'ApplicationUser' 到 'Microsoft.AspNertCore.Identity.IdentityUser. 的 implocot 引用转换
  • @Harry 看看新的更新,希望对您有所帮助。
【解决方案2】:
using (var db = new TenantDBContext("connectionString"))
{
    db.Database.Migrate();
    var store = new UserStore<IdentityUser>(db);
    var user = new IdentityUser("test");
    var result = await store.CreateAsync(user);
}

【讨论】:

    【解决方案3】:

    我认为您引用了错误的程序集。

    其构造函数只接收一个参数UserStore的UserManager类不是ASP.Net Core UserManager,它是ASP.Net UserManager。请检查以下详细信息,

    ASP.Net 用户管理器 (Microsoft.AspNet.Identity.Core.dll): https://msdn.microsoft.com/en-us/library/dn468199(v=vs.108).aspx

    ASP.Net Core UserManager(Microsoft.AspNetCore.Identity.dll、Microsoft.Extensions.Identity.Core.dll): https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.usermanager-1?view=aspnetcore-2.0

    所以我的建议是,修复您的身份库引用以使用 .Net Core 之一。

    【讨论】:

    • 如果我理解正确,您的建议是在 .Net Core 项目中使用 .Net 库?我不确定这是否可行,但我绝对不会推荐它。
    • 您误会了,请正确阅读问题,根据所述错误消息,很明显他正在为他的 .net 核心项目使用 .net 库。所以我的建议是修复引用以使用 .net 核心。
    猜你喜欢
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 2016-11-09
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多