Ninject conditional binding based on parameter type

我是研究僧i 提交于 2019-12-03 12:43:42

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()...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!