何らかの処理に基づいて実行時にオブジェクトを挿入して作成するにはどうすればよいですか?Ninjectを使用していくつかの処理に基づいて実行時にオブジェクトを挿入/作成するにはどうすればよいですか?
以下のコードでは、簡略化のためにメインの電卓(GridCalculator
)はPricesCalculator
に依存しています。しかし、いくつかの処理は、まずPriceCalculatorのインスタンス化の前にメインの計算機で実行する必要があります。 PricesCalculator
のGridPortfolios
プロパティは常に実行時にしか知ることができません。私は実行時にこのプロパティの値を設定する方法がわかりません(私は他の2つのコンストラクタ引数については心配していませんvalDatePrices
& edDatePrices
)。
Ninjectを使用してこのオブジェクトの作成を処理したいと思います。これは、依存関係が正しく設定されているためです。次のように
マイNinjectのセットアップは次のとおりです。私のNinjectモジュールの
Load
方法
public override void Load()
{
Bind<IFileReader<IList<Prices>>>().To<PricesReader>().Named("ValDatePrices");
Bind<IFileReader<IList<Prices>>>().To<PricesReader>().Named("EDDatePrices");
Bind<IFileReader<IEnumerable<GridRow>>>().ToMethod(GridReader);
/* other declarations*/
Bind<ICalculator<PriceSet>>().To<PricesCalculator>(); // this is probably not correct
Bind<ICalculator<IList<GridExposure>>>().To<GridCalculator>();
}
EDGridCalculator
public class GridCalculator : ICalculator<IList<GridExposure>>
{
public ICalculator<PriceSet> PricesCalculator { get; set; }
// not sure if constructor injection is the way to go
public GridCalculator(
ICalculator<PriceSet> pricesCalculator
, IFileReader<IEnumerable<GridRow>> gridReader)
{
this.PricesCalculator = pricesCalculator;
this.GridReader = gridReader;
}
public void Calculate()
{
var gdResults = GridReader().Read();
var pivot = new Pivot(gdResults);
IList<string> keys = pivot.Keys();
// Need my PricesCalculator object to be constructed
// with the "keys" variable and the other dependencies noted in Load()
// Continue to use "pivot" at later stages of processing.
}
}
PriceCalculator
public class PriceCalculator: ICalculator<PriceSet>{
[Inject] public IList<string> GridPortfolios;
PriceSet _priceSet;
public PricesCalculator(
[Named("ValDatePrices")]IFileReader<IList<Prices>> valDatePrices
, [Named("EDDatePrices")]IFileReader<IList<Prices>> edDatePrices
/* we could do constructor injection */
)
{
this.ValDatePricesReader = valDatePrices;
this.EDDatePricesReader = edDatePrices;
_priceSet = new PriceSet();
}
public void Calculate()
{ // calcs happen here
Result = new PriceSet();
}
}
メソッド注入について考えましたか? – Jeroen
私の答えは、価格計算機のインターフェースを変更できると仮定しています。これが当てはまらない場合、私はあなたに別の解決策を与えることができます –