Ninject UserManager和UserStore

使用ninject将UserManager和UserStore注入控制器的最优雅方法是什么? 例如,可以像这样注入上下文:

kernel.Bind().ToSelf().InRequestScope(); public class EmployeeController : Controller { private EmployeeContext _context; public EmployeeController(EmployeeContext context) { _context = context; } 

ninject可以用一行代码将UserManager和UserStore注入控制器吗?! 如果没有,最简单的方法是什么? 我不想用这个:

  var manager = new UserManager(new UserStore(new ApplicationDbContext())); 

先感谢您。

当然,您只需要确保所有依赖项的绑定( ApplicationDbContextUserManagerUserStore )。 绑定开放generics是这样完成的:

 kernel.Bind(typeof(UserStore<>)).ToSelf().InRequestScope(); // scope as necessary. 

如果它有一个接口,你就像这样绑定它:

 kernel.Bind(typeof(IUserStore<>)).To(typeof(UserStore<>)); 

所以,通过这些绑定你应该很高兴:

 kernel.Bind().ToSelf().InRequestScope(); kernel.Bind(typeof(UserManager<>)).ToSelf(); // add scoping as necessary kernel.Bind(typeof(UserStore<>)).ToSelf(); // add scoping as necessary 

花了8个小时试图弄清楚这一个,我想我有它。 在其他实现中可能需要修改的一个区别是SharedContext。 我的代码有一个inheritance自DBContext的SharedContext。

 kernel.Bind(typeof(DbContext)).To(typeof(SharedContext)).InRequestScope(); kernel.Bind(typeof(IUserStore)).To(typeof(UserStore)).InRequestScope(); kernel.Bind(typeof(UserManager)).ToSelf().InRequestScope(); 

我还对AccountController进行了更改。

 //public AccountController() // : this(new UserManager(new UserStore(new SharedContext()))) //{ //} public AccountController(UserManager userManager, UserStore userStore) { _userStore = userStore; _userManager = userManager; } private UserManager _userManager { get; set; } private UserStore _userStore { get; set; } 

希望这能节省一些时间。