为 ASP.NET Identity 配置 Unity DI

2024-02-22

我成功地使用 Unity 进行所有常规构造函数注入(例如存储库等),但无法使其与 ASP.NET Identity 类一起使用。设置是这样的:

public class AccountController : ApiController
{
    private UserManager<ApplicationUser> _userManager { get; set; }

    public AccountController(UserManager<ApplicationUser> userManager)
    {
        if (userManager == null) { throw new ArgumentNullException("userManager"); }
        _userManager = userManager;
    }

    // ...
}

Unity 的这些配置:

unity.RegisterType<AccountController>();
unity.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
unity.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager());

这与 Autofac、Ninject 等其他帖子相同,但在我的情况下不起作用。错误信息是:

尝试创建“AccountController”类型的控制器时发生错误。确保控制器具有无参数公共构造函数。 手动创建当然有效:

public AccountController()
    : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>("Mongo")))
{
}

怎么了?

UPDATE

正如 @emodendroket 所建议的,将代码缩短为这样就可以了。不需要Unity.Mvc包。

unity.RegisterType<IUserStore<IdentityUser>, 
  MyCustomUserStore>(new HierarchicalLifetimeManager());

and

public AccountController(UserManager<IdentityUser> _userManager,
  IAccountRepository _account)
{
    // ...

您还需要解决用户管理器。下面是一个示例,您可以如何使用用户管理器角色管理器。在此示例中,我使用常规 Unity 3 软件包,而不是其中一种衍生程序或引导程序(过去使用它们存在一些问题)。

账户控制器

private readonly UserManager<ApplicationUser> _userManager;

private readonly RoleManager<IdentityRole> _roleManager;

public AccountController(IUserStore<ApplicationUser> userStore, IRoleStore<IdentityRole> roleStore)
{
  _userManager = new UserManager<ApplicationUser>(userStore);
  _roleManager = new RoleManager<IdentityRole>(roleStore);
}

Unity引导程序

var accountInjectionConstructor = new InjectionConstructor(new IdentitySampleDbModelContext(configurationStore));
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(accountInjectionConstructor);
container.RegisterType<IRoleStore<IdentityRole>, RoleStore<IdentityRole>>(accountInjectionConstructor);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为 ASP.NET Identity 配置 Unity DI 的相关文章

随机推荐