Can a Ninject binding be based on a URL/route value?

后端 未结 2 1818
被撕碎了的回忆
被撕碎了的回忆 2020-12-06 14:13

I have a single controller that I want to use for CRUD operations on two different entities which implement the same interface. I\'d like for Ninject to give it a different

相关标签:
2条回答
  • 2020-12-06 14:54

    The following worked for me, Getting A Specific value from a route

    kernel.Bind<IRepo>().ToMethod(ctx => 
    {
        var a = HttpContext.Current.Request.RequestContext.RouteData.Values["RouteDateValue"]
        if (a != null)
        {
            return new RepoA(a);
        }
    
        return new RepoB();
    })
    
    0 讨论(0)
  • 2020-12-06 15:00

    That's usually a design smell but you could define the binding like this:

    kernel.Bind<IRepo>().ToMethod(ctx => 
    {
        var a = HttpContext.Current.Request["a"];
        if (a == "b")
        {
            return new RepoA();
        }
    
        return new RepoB();
    }).InRequestScope();
    
    0 讨论(0)
提交回复
热议问题