问题描述
使用 ninject 将 UserManager 和 UserStore 注入控制器的最优雅的方法是什么?例如,上下文可以像这样注入:
What is the most elegant way to inject UserManager and UserStore into a controller using ninject? 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;
}
可以用一行代码将 UserManager 和 UserStore 注入控制器吗?!如果没有,最简单的方法是什么?我不想用这个:
Can ninject inject UserManager and UserStore with a one line of code into a controller?! If not, what is the easiest way?I don't want to use this:
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
提前致谢.
推荐答案
当然,你只需要确保所有依赖项都有绑定(ApplicationDbContext
, UserManager
code> 和 UserStore
).绑定开放泛型是这样完成的:
Sure thing, you only need to make sure there's bindings for all dependencies (ApplicationDbContext
, UserManager<T>
and 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
这篇关于Ninject UserManager 和 UserStore的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!