0

在控制器中使用新的 connectionString 进行更改后,我希望有一个刷新的 UserManager 对象DbContext,我已经在控制器中注入了该对象UserManager,但很明显,它将始终具有DbContext来自 DI 的最后一个引用,而不是新创建的dbcontext.

我已经尝试过如下。

this.DbContext = new ApplicationDbContext(Configuration, optionsBuilder.Options);
this._userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(DbContext), null, new PasswordHasher<ApplicationUser>(), null, null, null, null, null, null);

它工作正常,但缺少大部分UserManager功能,比如 _userManager.CheckPasswordAsync(user, loginModel.Password)我将大部分参数作为 null 传递。我应该怎么做才能以最简单的方式完全UserManger使用 new DbContext

4

2 回答 2

0

您可以尝试创建一个服务并在服务中使用 UserManger,然后使用 Startup.ConfigureServices 方法中的 Transient 操作来配置该服务。瞬态操作总是不同的,每次检索服务都会创建一个新实例。然后,您可以在控制器中使用此服务。请检查以下步骤:

创建一个 UserManagerRepository 服务(在此服务中,您可以创建方法并使用 UserManager 方法):

public interface IUserManagerRepository
{
    void Write(string message);
}
public class UserManagerRepository : IUserManagerRepository, IDisposable
{
    private bool _disposed;
    private readonly UserManager<IdentityUser> _userManager;

    public UserManagerRepository(UserManager<IdentityUser> userManager)
    {
        _userManager = userManager;
    }

    public void Write(string message)
    {
        // _userManager.ChangePasswordAsync()
        Console.WriteLine($"UserManagerRepository: {message}");
    }

    public void Dispose()
    {
        if (_disposed)
            return;

        Console.WriteLine("UserManagerRepository.Dispose");
        _disposed = true;
    }
}

在 Startup.ConfigureServices 方法中使用以下代码配置服务:

 services.AddTransient<IUserManagerRepository, UserManagerRepository>();

之后,在控制器操作方法中手动调用服务。

    public IActionResult Index()
    {
        var services = this.HttpContext.RequestServices;
        var log = (IUserManagerRepository)services.GetService(typeof(IUserManagerRepository));

        log.Write("Index method executing");
         
        var log2 = (IUserManagerRepository)services.GetService(typeof(IUserManagerRepository));

        log2.Write("Index method executing");
        var log3 = (IUserManagerRepository)services.GetService(typeof(IUserManagerRepository));

        log3.Write("Index method executing"); 
        return View();
    }

截图如下:

在此处输入图像描述

参考:

教程:在 .NET 中使用依赖注入

依赖注入指南

ASP.NET Core 中的依赖注入

于 2020-12-29T10:08:28.257 回答
-1

使用依赖注入,这就是所有提到的工具的使用方式。

private DbContext DbContext { get;}

private UserManager<IdentityUser> UserManager { get; } 

public MyController(DbContext dbContext, UserManager<IdentityUser> userManager)
{
    DbContext = dbContext;
    UserManager = userManager;
}

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-5.0

这是有关如何为 EF Core 设置依赖注入的页面:

https://docs.microsoft.com/en-us/ef/core/dbcontext-configuration/#dbcontext-in-dependency-injection-for-aspnet-core

假设您已经拥有services.AddDefaultIdentity(...)and services.AddDbContext(...),注入UserManagerandYourProjectDbContext本质上应该只在您的控制器中工作。

于 2020-12-28T08:53:17.520 回答