微软实践使用统一寄存器类型
本文关键字:寄存器 类型 微软 | 更新日期: 2023-09-27 18:04:42
我有几个场景,我很难映射类型。
场景1:
public AccountController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
{
}
public AccountController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
类型定义
public class ApplicationUser : IdentityUser
{
}
// Summary:
// Implements IUserStore using EntityFramework where TUser is the entity type
// of the user being stored
//
// Type parameters:
// TUser:
public class UserStore<TUser> : IUserLoginStore<TUser>, IUserClaimStore<TUser>, IUserRoleStore<TUser>, IUserPasswordStore<TUser>, IUserSecurityStampStore<TUser>, IUserStore<TUser>, IDisposable where TUser : global::Microsoft.AspNet.Identity.EntityFramework.IdentityUser
{
....
}
public class UserManager<TUser> : IDisposable where TUser : global::Microsoft.AspNet.Identity.IUser
{
....
}
试图映射
container.RegisterType(typeof(IUserStore<>), typeof(ApplicationUser));
container.RegisterType(typeof(IDisposable), typeof(UserManager<>));
错误:无法强制转换类型为"Main.Models"的对象。应用程序用户'键入' microsoft.asp.net . identity . iuserstore 1[Main.Models.ApplicationUser]'.
With out mapping, i get this error: The current type, Microsoft.AspNet.Identity.IUserStore
1[主.模型。ApplicationUser]是一个接口,不能被构造。您是否错过了类型映射?
场景2:
public RegisterController(
IUserDataStorage<HandyGuy> session)
{
this.handySession = session;
}
类型定义
public class HttpUserDataStorage<T> : IUserDataStorage<T>
where T : class
{
public T Access
{
get { return HttpContext.Current.Session[typeof(T).FullName] as T; }
set { HttpContext.Current.Session[typeof(T).FullName] = value; }
}
}
映射:未遂
container.RegisterType(typeof(IUserDataStorage<>), typeof(HttpUserDataStorage<>));
Error: No Error。但handsession中总是null。访问
感谢emodendroket帮助我解决了实体框架的下一个映射问题。
但是对于我的场景,我可以用两种方式映射类型
第一个 container.RegisterType(typeof(UserManager<>),
new InjectionConstructor(typeof(IUserStore<>)));
container.RegisterType<Microsoft.AspNet.Identity.IUser>(new InjectionFactory(c => c.Resolve<Microsoft.AspNet.Identity.IUser>()));
container.RegisterType(typeof(IUserStore<>), typeof(UserStore<>));
container.RegisterType<IdentityUser, ApplicationUser>(new ContainerControlledLifetimeManager());
container.RegisterType<DbContext, ApplicationDbContext>(new ContainerControlledLifetimeManager());
第二个
container.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager());
container.RegisterType<DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager());
如果你想在MVC5中实现统一的IOC,只需遵循以下几点
- 创建一个新项目asp.net mvc 5(非空)
- 使用unity=> install-package unit .mvc
- WIF(windows身份框架)在app 中被破坏
- 遵循这个优秀的教程
- 你需要注入所有的身份框架实体