gpt4 book ai didi

c# - Microsoft Practice 使用 Unity 寄存器类型

转载 作者:太空狗 更新时间:2023-10-30 00:07:32 27 4
gpt4 key购买 nike

我有几个场景很难映射类型。

场景 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.ApplicationUser”类型的对象转换为类型“Microsoft.AspNet.Identity.IUserStore1[Main.Models.ApplicationUser]”。
没有映射,我得到这个错误:当前类型 Microsoft.AspNet.Identity.IUserStore
1[Main.Models.ApplicationUser] 是一个接口(interface),无法构造。您是否缺少类型映射?

场景 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<>));

错误:没有错误。但我总是在 handySession.Access 中有 null

最佳答案

感谢 emodendroket 帮助我解决了 Entity Framework 的下一个映射问题。

但是对于我的场景,我可以用两种方式映射类型

第一个

 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());

关于c# - Microsoft Practice 使用 Unity 寄存器类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23810055/

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