簡體   English   中英

Ninject基於參數類型的條件綁定

[英]Ninject conditional binding based on parameter type

我正在使用工廠返回數據庫:

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)

我相信這是因為'。'只提供一個請求,我需要完整的上下文才能檢索實際參數值並檢查其類型。 我不知道該做什么,除了使用命名綁定,實際上實現工廠並將邏輯放在那里,即

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

在查看Ninject源代碼后,我發現以下內容:

  • a.Parameters.Single(b => b.Name == "connection")為您提供IParameter類型的IParameter ,而不是真實參數。

  • IParameter具有方法object GetValue(IContext context, ITarget target) ,它不需要null上下文參數(target可以為null)。

  • 我還沒有找到任何方法從Request獲取IContext(樣本中的變量a)。

  • Context類沒有無參數構造函數,因此我們無法創建新的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()內部獲取Context的信息會很好

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM