[英]Ninject UserManager and UserStore
What is the most elegant way to inject UserManager and UserStore into a controller using ninject? 使用ninject将UserManager和UserStore注入控制器的最优雅方法是什么? For example, the context can be injected like this: 例如,可以像这样注入上下文:
kernel.Bind<EmployeeContext>().ToSelf().InRequestScope();
public class EmployeeController : Controller
{
private EmployeeContext _context;
public EmployeeController(EmployeeContext context)
{
_context = context;
}
Can ninject inject UserManager and UserStore with a one line of code into a controller?! 可以使用一行代码将UserManager和UserStore注入控制器吗? If not, what is the easiest way? 如果没有,最简单的方法是什么? I don't want to use this: 我不想用这个:
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
Thank you in advance. 先感谢您。
Sure thing, you only need to make sure there's bindings for all dependencies ( ApplicationDbContext
, UserManager<T>
and UserStore<T>
). 当然,您只需要确保所有依赖项的绑定( ApplicationDbContext
, UserManager<T>
和UserStore<T>
)。 Binding open generics is done like this: 绑定开放泛型是这样完成的:
kernel.Bind(typeof(UserStore<>)).ToSelf().InRequestScope(); // scope as necessary.
if it would have an interface, you'd bind it like this: 如果它有一个接口,你就像这样绑定它:
kernel.Bind(typeof(IUserStore<>)).To(typeof(UserStore<>));
So, with these bindings you should be good to go: 所以,使用这些绑定你应该很高兴:
kernel.Bind<ApplicationDbContext>().ToSelf().InRequestScope();
kernel.Bind(typeof(UserManager<>)).ToSelf(); // add scoping as necessary
kernel.Bind(typeof(UserStore<>)).ToSelf(); // add scoping as necessary
Spent 8 hours trying to figure this one out, and I think I have it. 花了8个小时试图找出这个,我想我有它。 The one difference that might need to be modified in other implementations is the SharedContext. 在其他实现中可能需要修改的一个区别是SharedContext。 My code has a SharedContext that inherits from DBContext. 我的代码有一个继承自DBContext的SharedContext。
kernel.Bind(typeof(DbContext)).To(typeof(SharedContext)).InRequestScope();
kernel.Bind(typeof(IUserStore<ApplicationUser>)).To(typeof(UserStore<ApplicationUser>)).InRequestScope();
kernel.Bind(typeof(UserManager<ApplicationUser>)).ToSelf().InRequestScope();
I Also made changes to the AccountController. 我还对AccountController进行了更改。
//public AccountController()
// : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new SharedContext())))
//{
//}
public AccountController(UserManager<ApplicationUser> userManager, UserStore<ApplicationUser> userStore)
{
_userStore = userStore;
_userManager = userManager;
}
private UserManager<ApplicationUser> _userManager { get; set; }
private UserStore<ApplicationUser> _userStore { get; set; }
Hope this saves someone else some time. 希望这能节省一些时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.