2012-03-14 4 views
1

何らかの処理に基づいて実行時にオブジェクトを挿入して作成するにはどうすればよいですか?Ninjectを使用していくつかの処理に基づいて実行時にオブジェクトを挿入/作成するにはどうすればよいですか?

以下のコードでは、簡略化のためにメインの電卓(GridCalculator)はPricesCalculatorに依存しています。しかし、いくつかの処理は、まずPriceCalculatorのインスタンス化の前にメインの計算機で実行する必要があります。 PricesCalculatorGridPortfoliosプロパティは常に実行時にしか知ることができません。私は実行時にこのプロパティの値を設定する方法がわかりません(私は他の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(); 
    } 

} 
+1

メソッド注入について考えましたか? – Jeroen

+0

私の答えは、価格計算機のインターフェースを変更できると仮定しています。これが当てはまらない場合、私はあなたに別の解決策を与えることができます –

答えて

0

Hy これは、正しいインターフェイスを設計する場合に過ぎず、問題とは関係ありません。この場合、キーデータのコンストラクタインジェクションは使用しないでください。パラメータを取るために価格計算機の計算方法を変更するだけです。計算機はコンストラクターに注入されますが、価格計算ツールで計算を呼び出すと、必要なデータが渡されます。

ダニエル

関連する問題