当控制器具有属性时进行 Ninject 绑定
我有一个控制器,
[MyAttribute]
public class MyController: Controller
{
public MyController(InterfaceA a, InterfaceB b)
{
}
}
如果请求来自具有 MyAttribute 的控制器,我希望 InterfaceA 始终绑定到 ClassA。所以我打了电话。
Bind<InterfaceA>.To<ClassA>().WhenClassHas<MyAttribute>();
InterfaceB 的实例之一,ClassB,有一个像这样的构造函数。
public ClassB(InterfaceC c)
当被调用的控制器具有 MyAttribute 时,我希望 InterfaceC 绑定到 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);
}
I have a controller
[MyAttribute]
public class MyController: Controller
{
public MyController(InterfaceA a, InterfaceB b)
{
}
}
I wanted InterfaceA always to bind to ClassA if the request is coming from a controller with the MyAttribute. So I did a call.
Bind<InterfaceA>.To<ClassA>().WhenClassHas<MyAttribute>();
One of the instantiations of InterfaceB, ClassB, has a constructor like this.
public ClassB(InterfaceC c)
I want InterfaceC to bind to Class C when the called controller had the MyAttribute. However, my previous binding won't work, because the parent class is an intermediary class, not the controller itself. Is there anyway to write the binding so it will work from anywhere provided the calling controller had the attribute?
Edit: My solution using Remo's advice
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您可以,但必须使用
When(Funccondition)
代替并编写一些自定义代码。WhenClassHas 使用以下 Func:
您必须扩展它并使用
request.ParentRequest
在注入上下文中进行迭代Yes you can you must use
When(Func<IRequest, bool> condition)
instead and write some custom code.WhenClassHas uses the following Func:
You have to extend this and iterate up in the injection context using
request.ParentRequest