我使用工廠來返回一個datasender:Ninject條件基於參數類型的結合
Bind<IDataSenderFactory>()
.ToFactory();
public interface IDataSenderFactory
{
IDataSender CreateDataSender(Connection connection);
}
我有datasender的兩種不同的實現(WCF和遠程),其採取不同的類型:
public abstract class Connection
{
public string ServerName { get; set; }
}
public class WcfConnection : Connection
{
// specificProperties etc.
}
public class RemotingConnection : Connection
{
// specificProperties etc.
}
我想使用Ninject綁定這些特定類型的數據集根據從參數傳遞的連接類型。我曾嘗試以下失敗:
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));
}