我已經瀏覽了所有關於SO的問題,但似乎無法弄清楚我在這裏做錯了什麼。Microsoft身份證與身份證DI
我有以下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;
}
,並在我的賬戶控制器I如下注入;
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時,我得到錯誤;
分辨率依賴性的失敗,類型=「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調用是Static,所以我假設我將不得不將這個移動到DI的構造函數中?
任何人都可以解釋我在這裏東錯,如何解決?