Ninject注射根据一个路径数据值 [英] Ninject injection based on a route data value

查看:106
本文介绍了Ninject注射根据一个路径数据值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们已经有了一个ASP.NET MVC应用程序中,有许多不同的领域。有迹象表明,使用相同的C#类从我们的服务2层区域,但针对不同的基础数据。我想这些服务基于在路径数据的值,以得到不同的依赖关系。

We've got an ASP.NET MVC application, that has a number of different areas. There are 2 areas that use the same C# classes from our service layer, but target different underlying data. I want these services to get different dependencies based on a value in the route data.

这很难解释,而我转述我的课/地区名称。为了显示:

It's hard to explain, and I'm paraphrasing my class/area names. To illustrate:

当'code'是在路由的数据,我想注入时,它不是present不同的依赖。

When the 'Code' is in the route data, I want to get different dependencies injected to when it is not present.

我知道有你可以用做条件绑定。当()方法,但我不知道如何从那里得到的路由数据。我可能这样做,也是基于它从不过叫,面积那不是preferable在我的实例(我想我们可以用code。在其他地区)

I understand there is the .When() method you can use to do conditional bindings, but I'm not sure how to get the route data from there. I could possibly also do it based on the area that it was called from, however thats not preferable in my instance (I think we may use the Code in that other area)

这可能吗?

推荐答案

这对我的作品(它是标准的路由配置{控制器} / {行动} / {ID}

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

Ninject配置

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的路线:/家庭/指标/ 1 /家庭/指标/ 2等

  • ServiceB的路线:/,/家庭/指标等

这篇关于Ninject注射根据一个路径数据值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆