简体   繁体   English

如何在 ASP.NET Core 中更改 userManager 的 dbContext?

[英]How can I change the dbContext of userManager in ASP.NET Core?

I have two databases.我有两个数据库。

  • application_db应用数据库
  • registry_db注册表_数据库

application_db is used for the application to get work and uses the ApplicationDbContext . application_db用于应用程序获取工作并使用ApplicationDbContext

registry_db is used to manage all accounts. registry_db用于管理所有帐户。 I would like to create first an account over my registry service and then insert the created account (with less information) into application db .我想首先通过我的注册表服务创建一个帐户,然后将创建的帐户(信息较少)插入应用程序 db Registry_db is using RegistryDbContext . Registry_db 正在使用RegistryDbContext

I've injected both contexts successfully (ApplicationDbContext & RegistryDbContext) inside my registry service over the dependency injection.我已经通过依赖注入成功地在我的注册表服务中注入了两个上下文(ApplicationDbContext 和 RegistryDbContext)。

My Startup looks like this:我的启动看起来像这样:

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

Inside my registry service, I can get the userManager over the dependencies injection and create an account.在我的注册表服务中,我可以通过依赖项注入获取 userManager 并创建一个帐户。 On default the userManager uses the RegistryDbContext.默认情况下,userManager 使用 RegistryDbContext。 Once an account is created successfully over the registry service, I would like to create the same account in the application_db (over the ApplicationDbContext).通过注册表服务成功创建帐户后,我想在application_db (通过 ApplicationDbContext)中创建相同的帐户。 But I get stuck in this line of code但是我被这行代码卡住了

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

I get this error message:我收到此错误消息:

Error: There is no argument given that corresponds to the required format parameter 'optionsAccessor' of 'UserManager.错误:没有给出与“UserManager”的所需格式参数“optionsAccessor”相对应的参数。 UserManager(IUserStore, IOptions, IPasswordHasher, IEnumerable>, IEnumerable>, ILookupNormalizer, IdentityErrorDescriber, IServiceProbider, ILogger>)' UserManager(IUserStore, IOptions, IPasswordHasher, IEnumerable>, IEnumerable>, ILookupNormalizer, IdentityErrorDescriber, IServiceProbider, ILogger>)'

My ApplicationUser class looks like this:我的 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; }
}

What is wrong or missing?有什么问题或遗漏了什么? I tried already to follow this post here but no luck.我已经尝试在这里关注这篇文章但没有运气。 Is there an other way to create an userManager instance with an other context?有没有其他方法可以使用其他上下文创建 userManager 实例?

It is dependency injection over constructor.它是对构造函数的依赖注入。 With DI, you shouldn't initialize your service directly.使用 DI,您不应该直接初始化您的服务。 You should register your Service and ApplicationContext in Startup.cs .您应该在Startup.cs注册您的 Service 和 ApplicationContext。

When you need your Service, you should inject it over constructor into a controller, and DI chain will automatically inject instance of ApplicationContext into the Service.当你需要你的服务时,你应该通过构造函数将它注入控制器,DI 链会自动将 ApplicationContext 的实例注入服务。

Of course, if you don't need your service for each method in a controller, you can initialize it into method :当然,如果您不需要为控制器中的每个方法提供服务,您可以将其初始化为 method :

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

However what you really need to do is to implement your own version of UserManagerFactory which this link might be of help.但是,您真正需要做的是实现您自己的UserManagerFactory版本, 此链接可能会有所帮助。

this post might help too.这篇文章也可能有所帮助。

PS :附注:

Take a look at @Singularity222 answer in this thread.看看这个线程中的@Singularity222答案。 he has done the same thing you wanna do, in his repo .他在他的 repo 中做了你想做的同样的事情。

Also we have this thread where the owner of Identity project (!) said you need to implement your own version of UserStore .我们还有这个帖子,其中Identity 项目所有者(!) 说您需要实现自己的UserStore版本。

I think you are referencing the wrong assembly.我认为您引用了错误的程序集。

The UserManager class which its constructor receive only one argument UserStore is not ASP.Net Core UserManager, it is ASP.Net UserManager.其构造函数仅接收一个参数 UserStore 的 UserManager 类不是 ASP.Net Core UserManager,而是 ASP.Net UserManager。 Please check the following details,请检查以下详细信息,

ASP.Net UserManager (Microsoft.AspNet.Identity.Core.dll): https://msdn.microsoft.com/en-us/library/dn468199(v=vs.108).aspx 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 ASP.Net 核心用户管理器(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

So my suggestion is, fix your identity library reference to use .Net Core one.所以我的建议是,修复您的身份库引用以使用 .Net Core 之一。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET Core 2:UserManager与DbContext - ASP.NET Core 2: UserManager vs. DbContext 如何利用 ASP.NET Core LifeCycle 之外的 DbContext 池? - How can I take advantage of the DbContext Pooling out of ASP.NET Core LifeCycle? 如何从ASP.NET Core中的DbContext获取IHostingEnvironment - How can I get IHostingEnvironment from DbContext in ASP.NET Core ASP.NET Core 如何让 UserManager 在控制器中工作? - ASP.NET Core How to get UserManager working in controller? 如何将UserManager注入到ASP.NET Core 2.0中的另一个服务 - How to inject UserManager to another service in ASP.NET Core 2.0 ASP.NET Core 2.0如何在策略中访问UserManager? - ASP.NET Core 2.0 How to access UserManager in a policy? 如何正确使用依赖注入在 Blazor 组件上包含 asp.net 核心标识 UserManager? - How do I properly use dependency injection to include asp.net core identity UserManager on a Blazor component? 实体框架6和Asp.Net Identity UserManager:多个DbContext - Entity Framework 6 and Asp.Net Identity UserManager: Multiple DbContext 在ASP.NET核心中使用时,如何从另一个项目访问EF核心的DbContext? - How to I access the DbContext of EF core from another project when used in ASP.NET core? 如何在 ASP.NET Core 5 中使用动态 DBContext 作为参数 - How to use dynamic DBContext as parameter in ASP.NET Core 5
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM