Ninject UserManager and UserStore

本文关键字:UserStore and UserManager Ninject | 更新日期: 2023-09-27 18:06:06

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

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

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

 var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

提前感谢。

Ninject UserManager and UserStore

当然,你只需要确保所有依赖项(ApplicationDbContext, UserManager<T>UserStore<T>)都有绑定。绑定开放泛型的操作如下:

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

如果它有接口,你可以这样绑定它:

kernel.Bind(typeof(IUserStore<>)).To(typeof(UserStore<>));
所以,有了这些绑定,你应该很好:
kernel.Bind<ApplicationDbContext>().ToSelf().InRequestScope();
kernel.Bind(typeof(UserManager<>)).ToSelf(); // add scoping as necessary
kernel.Bind(typeof(UserStore<>)).ToSelf(); // add scoping as necessary

花了8个小时想弄清楚这个问题,我想我找到了。在其他实现中可能需要修改的一个不同点是SharedContext。我的代码有一个继承自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(); 

我还更改了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; }