Parameter binding in ninject 2.0

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 the 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 am having trouble determining the correct 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 the value of the passed parameter. I need to pass an instance of IContext to the GetValue method, but I don’t know how to get a valid instance of IContext. Or maybe there is a better way to accomplish my task?

EDIT: BindingMetadata is the best way to solve my problem. See Context bindings with Ninject 2.0 for more details.

Hi

+3
source share
2 answers

IRequest.ParentContext ?

, , , - [ DI IDeity], Get WithName Bind.

: Reflector, . , -, , , . ( Context ctor), factory.

( ). .. Get - :

_kernel.Get<ITarget>( (Ninject.Planning.Bindings.BindingMetadata metadata)=>metadata.Has("x") );

, @Ian Davis , : D

+2

IIRC . , , - , Get. null IContext, . , ctx = > value β†’ , , .

+1

Source: https://habr.com/ru/post/1737525/


All Articles