Ninject injection based on a route data value

风格不统一 提交于 2019-11-28 09:30:20

This works for me (it is for 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;
}

it will use

  • ServiceA for routes: /home/index/1, /home/index/2 etc.
  • ServiceB for routes: / , /home/index etc.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!