Ninject context binding on MVC request

I have an unusual situation when you enter a service in ASP.NET MVC Controller. The controller provides one action to display the sidebar menu on the page, and the service entered into the controller provides a factory to create the contents of the sidebar. The action is decorated with an attribute [ChildActionOnly]: the sidebar can only be displayed when rendering another action.

The difficulty is that I want to insert different instances of the abstraction of the factory sidebar according to the requested page (= Controller). I used to do this using a kind of abstract factory that had an inelegant implementation of using the controller name string to determine which particular factory implementation to use; Now I have translated this to the correct abstract factory and therefore you need to move the selection of type factory to another location.

My Ninject bindings are currently defined very simply:

Kernel.Bind<ISideBarFactory>().To<FooSideBarFactory>().InRequestScope();
Kernel.Bind<ISideBarFactory>().To<DefaultSideBarFactory>().InRequestScope();

and when I add more controllers, I will add more instances of the first row. I would like to see this work:

  • /foo/action request received
    • Ninject associates ISideBarFactorywith FooSideBarFactoryand introduces intoSideBarController
  • /bar/action request received
    • Ninject associates ISideBarFactorywith BarSideBarFactoryand introduces intoSideBarController
  • /baz/action received request
    • BazSideBarFactory , Ninject ISideBarFactory , DefaultSideBarFactory SideBarController

- Ninject , , , , , - , , , .

+3
1

Contextual-Binding

// default binding - used if none of the conditions is met
kernel.Bind<IService>()
    .To<DefaultService>()

kernel.Bind<IService>()
    .To<BasicService>()
    .When(x=> IsRouteValueDefined("controller", "Service"));

kernel.Bind<IService>()
    .To<ExtraService>()
    .When(x=> IsRouteValueDefined("controller", "ExtraService"));

IsRouteValueDefined()

true, routeValue null.

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().ToUpper() == routeValue.ToUpper();
}
+3

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


All Articles