I want to use conditional binding in ninject, based on passed parameters. I have something like below:
public class Subject
{
}
public interface ITarget
{
}
public class Target1 : ITarget
{
}
public class Target2 : ITarget
{
}
And now I need to instantiate ITarget interface:
public void MethodName(IKernel kernel)
{
ITarget target1 = kernel.Get<ITarget>(new Parameter("name", new Subject(), true)); // Should be instance of Target1
ITarget target2 = kernel.Get<ITarget>(); // Should be instance of Target2
}
I have problems to define proper bindings. I tried the following:
kernel.Bind<ITarget>().To<Target1>().When(Predicate);
kernel.Bind<ITarget>().To<Target2>();
private bool Predicate(IRequest request)
{
IParameter parameter = request.Parameters.Count == 0 ? null : request.Parameters[0];
if (parameter == null)
{
return false;
}
object parameterValue = parameter.GetValue( /*what to put here?*/);
return parameterValue != null && parameterValue.GetType().IsAssignableFrom(typeof(Subject));
}
but I don't know how to get value of passed parameter. I need to pass IContext instance to GetValue method, but don't know how to get valid instance of IContext. Or maybe there is better way to accomplish my task?
EDIT: BindingMetadata is better way to solve my problem. See http://stackoverflow.com/questions/2507881/contextual-bindings-with-ninject-2-0 for details
Regards