gpt4 book ai didi

c# - 为 ASP.NET 身份配置 Unity DI

转载 作者:IT王子 更新时间:2023-10-29 04:47:42 27 4
gpt4 key购买 nike

我成功地将 Unity 用于所有常规构造函数注入(inject),例如存储库等,但我无法让它与 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,但它不适用于我的情况。错误信息是:

An error occurred when trying to create a controller of type 'AccountController'. Make sure that the controller has a parameterless public constructor. Manual creation works of course:

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

怎么了?

更新

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

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

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

最佳答案

您还需要解析 UserManager。以下是如何使用 UserManagerRoleManager 执行此操作的示例。在此示例中,我使用常规的 Unity 3 程序包,而不是派生程序或 Bootstrap 之一(过去使用它们时遇到过一些问题)。

账户 Controller

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 Bootstrap

var accountInjectionConstructor = new InjectionConstructor(new IdentitySampleDbModelContext(configurationStore));
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(accountInjectionConstructor);
container.RegisterType<IRoleStore<IdentityRole>, RoleStore<IdentityRole>>(accountInjectionConstructor);

关于c# - 为 ASP.NET 身份配置 Unity DI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21927785/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com