8

我正在使用工厂返回数据发送器:

Bind<IDataSenderFactory>()
    .ToFactory();

public interface IDataSenderFactory
{
    IDataSender CreateDataSender(Connection connection);
}

我有两种不同的数据发送器实现(WCF 和远程处理),它们采用不同的类型:

public abstract class Connection
{
    public string ServerName { get; set; }
}

public class WcfConnection : Connection
{
    // specificProperties etc.
}

public class RemotingConnection : Connection
{
    // specificProperties etc.
}

我正在尝试使用 Ninject 根据从参数传递的 Connection 类型来绑定这些特定类型的数据发送器。我尝试了以下失败:

Bind<IDataSender>()
    .To<RemotingDataSender>()
    .When(a => a.Parameters.Single(b => b.Name == "connection") as RemotingConnection != null)

我相信这是因为 '.When' 只提供一个请求,我需要完整的上下文才能检索实际参数值并检查其类型。我不知道该做什么,除了使用命名绑定,实际实现工厂并将逻辑放在那里,即

public IDataSender CreateDataSender(Connection connection)
{
    if (connection.GetType() == typeof(WcfConnection))
    {
        return resolutionRoot.Get<IDataSender>("wcfdatasender", new ConstructorArgument("connection", connection));
    }

    return resolutionRoot.Get<IDataSender>("remotingdatasender", new ConstructorArgument("connection", connection));
}
4

1 回答 1

7

在研究了 Ninject 源代码后,我发现了以下内容:

  • a.Parameters.Single(b => b.Name == "connection")给你类型的变量IParameter,而不是真正的参数。

  • IParameter具有object GetValue(IContext context, ITarget target)不需要空上下文参数的方法(目标可以为空)。

  • 我还没有找到从 Request 中获取 IContext 的任何方法(您的示例中的变量 a )。

  • Context类没有无参数构造函数,所以我们不能创建新的上下文。

为了使其工作,您可以创建虚拟 IContext 实现,例如:

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

而不是使用它

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

如果有人可以发布一些有关从内部获取上下文的信息,那就太好了When()......

于 2013-03-07T12:03:44.293 回答