这对我有用(适用于标准路线配置"{controller}/{action}/{id}"
)
注入配置
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;
}
它将使用
- 用于路由的 ServiceA:/home/index/1、/home/index/2 等。
- 路线的 ServiceB: / , /home/index 等。