控制器具有属性时的Ninject绑定

DMu*_*gan 1 ninject asp.net-mvc-3

我有一个控制器

[MyAttribute]
public class MyController: Controller
{
    public MyController(InterfaceA a, InterfaceB b)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

如果请求来自具有MyAttribute的控制器,我希望InterfaceA始终绑定到ClassA.所以我打了个电话.

Bind<InterfaceA>.To<ClassA>().WhenClassHas<MyAttribute>();
Run Code Online (Sandbox Code Playgroud)

InterfaceB的一个实例化,ClassB,有一个像这样的构造函数.

public ClassB(InterfaceC c)
Run Code Online (Sandbox Code Playgroud)

我希望InterfaceC在被调用的控制器具有MyAttribute时绑定到C类.但是,我以前的绑定不起作用,因为父类是中间类,而不是控制器本身.反正有没有写绑定所以如果调用控制器具有属性,它将在任何地方工作?

编辑:我的解决方案使用雷莫的建议

public static IBindingInNamedWithOrOnSyntax<TBinding> WhenControllerHasAttribute<TBinding>(this IBindingWhenSyntax<TBinding> instance, Type type)
{
    Func<IRequest, bool> hasAttribute = (request) =>
    {
        while (request.ParentRequest.Target != null)
        {
            request = request.ParentRequest;
        }
        return request.Target.Member.ReflectedType.IsDefined(type, false);
    };
    return instance.When(hasAttribute);
}
Run Code Online (Sandbox Code Playgroud)

Rem*_*oor 5

是的,您必须使用When(Func<IRequest, bool> condition)而是编写一些自定义代码.

WhenClassHas使用以下Func:

request => request.Target.Member.ReflectedType.HasAttribute(attributeType)
Run Code Online (Sandbox Code Playgroud)

您必须扩展它并使用注入上下文迭代 request.ParentRequest