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);
}
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