我已经搜索了所有关于SO的问题,但似乎无法弄清楚我在这里做错了什么。
我有以下UserService
public class UserService : BaseService
{
private readonly Func<UserManager<ApplicationUser>> _userManagerFactory;
private readonly Func<RoleManager<IdentityRole>> _roleManagerFactory;
public UserService(Func<UserManager<ApplicationUser>> userManagerFactory, Func<RoleManager<IdentityRole>> roleManagerFactory)
{
_userManagerFactory = userManagerFactory;
_roleManagerFactory = roleManagerFactory;
}
并在我的帐户控制器中我注入如下;
public class AccountsController : ApiController
{
[Dependency]
public UserService UserService { get; set; }
现在在我的UnityConfig.cs中,我将DI设置如下;
var userInjectionConstructor = new InjectionConstructor(new MyDataContext());
//container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(userInjectionConstructor);
container.RegisterType<UserManager<ApplicationUser>, ApplicationUserManager>();
container.RegisterType<IRoleStore<IdentityRole, string>, RoleStore<IdentityRole>>(userInjectionConstructor);
ApplicationUserManager如下所示;
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var container = (IUnityContainer)Startup.HttpConfiguration.DependencyResolver.GetService(typeof(IUnityContainer));
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(new MyDataContext()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
这会编译并运行,但是当我尝试解析DI时会出现错误;
依赖项的解析失败,类型=&#34; Microsoft.AspNet.Identity.UserManager
1[CCS.Core.ApplicationUser]", name = "(none)". Exception occurred while: while resolving. Exception is: InvalidOperationException - The current type, Microsoft.AspNet.Identity.IUserStore
1 [CCS.Core.ApplicationUser]是一个无法构造的接口。你错过了类型映射吗?
现在引发了这个问题,因为如果我使用以下内容;
var userInjectionConstructor = new InjectionConstructor(new MyDataContext());
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(userInjectionConstructor);
然后DI工作,但是没有ApplicationUserManager设置(令牌提供程序等)。
现在ApplicationUserManager.Create调用是静态的,所以我假设我必须将它移动到DI的构造函数中?
任何人都可以解释我在这里错了什么以及如何解决?
答案 0 :(得分:1)
还有一个问题就是让用户拥有角色名称,无论如何在尝试解决这个问题时我偶然发现了这个博客,它完全解释了如何注入http://tech.trailmax.info/2014/09/aspnet-identity-and-ioc-container-registration/。
祝你好运!