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

I have one controller that I want to use for CRUD operations on two different objects that implement the same interface. I would like Ninject to provide it with a different repository based on the value of the query string in the URL (or, possibly, another URL redirected to the same controller). Is it possible? How can i do this?

+4
source share
2 answers

Typically, the design is odorless, but you can define a binding like this:

kernel.Bind<IRepo>().ToMethod(ctx => { var a = HttpContext.Current.Request["a"]; if (a == "b") { return new RepoA(); } return new RepoB(); }).InRequestScope(); 
+7
source

The following worked for me, getting the specific value from the 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
source

Source: https://habr.com/ru/post/1437211/


All Articles