【问题标题】:Ninject UserManager and UserStoreNinject UserManager 和 UserStore
【发布时间】:2014-05-31 08:33:51
【问题描述】:

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

 kernel.Bind<EmployeeContext>().ToSelf().InRequestScope();

    public class EmployeeController : Controller
    {
    private EmployeeContext _context;

    public EmployeeController(EmployeeContext context)
    {
        _context = context;
    }

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

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

提前谢谢你。

【问题讨论】:

    标签: c# model-view-controller controller ninject


    【解决方案1】:

    当然,您只需要确保所有依赖项(ApplicationDbContextUserManager&lt;T&gt;UserStore&lt;T&gt;)都有绑定。绑定开放泛型是这样完成的:

    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
    

    【讨论】:

    • @BatteryBackupUnit...谢谢。最后一个问题......我如何将它们注入控制器?我可以注入上下文,但不确定 Usermanager 和 Userstore
    • 为什么不能以与上下文完全相同的方式进行操作?我非常肯定它应该工作。如果不是,请提供确切的代码/异常日志...
    • 这是新问题:stackoverflow.com/questions/23991796/… 我想替换 var manager = new UserManager(new UserStore(new ApplicationDbContext()));我可以替换上下文,但不知道如何替换UserManager、UserStore
    • 谢谢,它成功了。我必须将 IUserStore 绑定到 UserStore 才能使其工作。
    【解决方案2】:

    花了 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; }
    

    希望这可以节省其他人一些时间。

    【讨论】:

    • 我认为这很好。当我回到这段代码时,我会实现它。
    猜你喜欢
    • 2016-07-31
    • 2017-06-12
    • 2015-08-07
    • 2016-12-13
    • 1970-01-01
    • 2017-07-05
    • 2014-08-13
    • 2014-10-23
    • 1970-01-01
    相关资源
    最近更新 更多