Ninject conditional binding based on parameter type

后端 未结 1 2093
误落风尘
误落风尘 2021-02-15 18:11

I\'m using a factory to return a datasender:

Bind()
    .ToFactory();

public interface IDataSenderFactory
{
    IDataSender CreateData         


        
相关标签:
1条回答
  • 2021-02-15 18:39

    After some looking into Ninject source I have found following:

    • a.Parameters.Single(b => b.Name == "connection") gives you variable of type IParameter, not real parameter.

    • IParameter has method object GetValue(IContext context, ITarget target) that requires not null context parameter (target can be null).

    • I have not found any way to get IContext from Request (variable a in your sample).

    • Context class does not have parameterless constructor so we can't create new Context.

    To make it work you can create dummy IContext implementation like:

    public class DummyContext : IContext
    {
        public IKernel Kernel { get; private set; }
        public IRequest Request { get; private set; }
        public IBinding Binding { get; private set; }
        public IPlan Plan { get; set; }
        public ICollection<IParameter> Parameters { get; private set; }
        public Type[] GenericArguments { get; private set; }
        public bool HasInferredGenericArguments { get; private set; }
        public IProvider GetProvider() { return null; }
        public object GetScope() { return null; }
        public object Resolve() { return null; }
    }
    

    and than use it

    kernel.Bind<IDataSender>()
          .To<RemotingDataSender>()
          .When( a => a.Parameters
                       .Single( b => b.Name == "connection" )
                       .GetValue( new DummyContext(), a.Target ) 
                   as RemotingConnection != null );
    

    It would be nice if someone could post some info about obtaining Context from inside When()...

    0 讨论(0)
提交回复
热议问题