Ninject injection based on route data value

We have an ASP.NET MVC application that has several different areas. There are 2 areas that use the same C # classes at our service level, but target different baseline data. I want these services to receive different dependencies based on the value in the route data.

It is hard to explain, and I am retelling the names of my class / area. Illustrate: Call logic

When the "Code" is in the route data, I want to get different dependencies entered when they are not there.

I understand that there is a .When () method that you can use for conditional bindings, but I'm not sure how to get route data from there. I could also do this based on the area from which it was called, however this is not preferred in my case (I think we can use Codex in this other area)

Is it possible?

+3
source share
1 answer

This works for me (this is for the standard route configuration "{controller}/{action}/{id}" )

Ninject Configuration

 protected override Ninject.IKernel CreateKernel() { var kernel = new StandardKernel(); kernel.Bind<IService>() .To<ServiceA>() .When(x => IsRouteValueDefined("id", null)); kernel.Bind<IService>() .To<ServiceB>() .When(x => !IsRouteValueDefined("id",null)); return kernel; } // just sample condition implementation public static bool IsRouteValueDefined(string routeKey, string routeValue) { var mvcHanlder = (MvcHandler)HttpContext.Current.Handler; var routeValues = mvcHanlder.RequestContext.RouteData.Values; var containsRouteKey = routeValues.ContainsKey(routeKey); if (routeValue == null) return containsRouteKey; return containsRouteKey && routeValues[routeKey].ToString() == routeValue; } 

he will use

  • ServiceA for routes: / home / index / 1, / home / index / 2, etc.
  • ServiceB for routes: /, / home / index, etc.
+1
source

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


All Articles