【问题标题】:Create UserManager in Class library在类库中创建 UserManager
【发布时间】:2021-11-17 05:21:06
【问题描述】:

我正在使用 Blazor 和 .NetCore 开发应用程序。

我将 Microsoft 标识用于角色和用户。在 Visual Studio 生成的基础项目中,使用标识的代码默认是构造的。对于项目的目标,我正在使用这种模式设计:

我需要将身份的 CRUD 移动到“业务类库”。为此我需要创建一个UserManager和RoleManager,但我不知道要创建UserManager(因为构造函数,需要8个参数)

namespace Business
{
public static class B_Manage
{
    public static void CreateUser()
    {
        using (var IdentityDB = new IDBContext())
        {
            var roleStore = (IRoleStore<IdentityRole>)new RoleStore<IdentityRole>(IdentityDB);
            var roleManager = new RoleManager<IdentityRole>(roleStore, null, null, null, null);

            var userStore = new UserStore<IdentityUser>(IdentityDB);
            var userManager = new UserManager<IdentityUser>()

        }
    }

} 

}

我在其他网站看到了示例代码,但是当我参加创建一个新实例时,需要其他变量。

 public async Task<ActionResult> Index()
    {
        var context = new ApplicationDbContext(); // DefaultConnection
        var store = new UserStore<CustomUser>(context);
        var manager = new UserManager<CustomUser>(store);
     }

有人知道我可以在类库中创建 UserManager 吗?

【问题讨论】:

    标签: .net-core asp.net-identity blazor usermanager


    【解决方案1】:

    您无需创建新的UserManager&lt;T&gt;RoleManager&lt;T&gt;,而是需要从托管应用的服务集合中通过依赖注入进行注入。

    要注入您的类的构造函数,您可以使用下面的UserManager 示例:

    public class SomeClass
    {
        private readonly UserManager<ApplicationUser> _userManager;
    
        public SomeClass(
            UserManager<ApplicationUser> userManager)
        {
            _userManager = userManager;
        }
    
    ...
    

    -或-

    你将这个 via 参数传递给你的方法。

    public void DoSomething(UserManager<ApplicationUser> userManager)
    {
        ....
    }
    

    您可以从这里获得一些帮助:

    【讨论】:

    • 感谢您提供的信息,非常感谢,
    • 想象一下,如果我通过依赖注入使用 UserManager,我不会在生成密码哈希时遇到问题
    • 您不会有任何问题,因为所有正确的服务都将在 DI 中以使身份工作。
    猜你喜欢
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多