2010-11-22 8 views
1

私は正しい用語を使用していますが、ASP.NET Webアプリケーションでさまざまなデータソースを使用してオブジェクトを返すコントローラクラスがいくつかあります。 ie"コントローラ"クラスをロード/選択する最良の方法は何ですか

Product p = ProductController.GetByID(string id); 

私ができることをしたいのは、異なるProductControllersから選択できるコントローラファクトリを使用することです。私は基本的な工場パターンを理解していますが、選択されたcotrollerクラスを単なる文字列でロードする方法があるのだろうかと思っていました。

私が達成したいのは、ファクトリクラスを更新することなく、新しい/異なるコントローラを返す方法です。誰かが私が依存性注入とMEFを見るように勧めました。私はMEFを見ていましたが、これをWebアプリケーションに組み込む方法を理解するのに問題がありました。

私は正しい方向にいくつかのポインタを取得したいと思います。

答えて

1

これを解決する方法はたくさんあります。依存性注入を行うためのフレームワークは必要ありません(ハンドコーディングではIoCコンテナが意味を持ち始めるかもしれませんが)。

複数の実装でGetByIDを呼び出す必要があるので、私はあなたが持っているProductControllerからインターフェイスを抽出することから始めます。そこから

public interface IProductController 
    { 
     Product GetByID(int id); 
    } 

    public class SomeProductController : IProductController 
    { 
     public Product GetByID(int id) 
     { 
      return << fetch code >> 
     } 
    } 

あなたはいくつかの方法で実装を解決することができ、いくつかの例:

public class ProductFetcher 
{ 
    // option 1: constructor injection 
    private readonly IProductController _productController; 

    public ProductFetcher(IProductController productController) 
    { 
     _productController = productController; 
    } 
    public Product FetchProductByID(int id) 
    { 
     return _productController.GetByID(id); 
    } 

    // option 2: inject it at the method level 
    public static Product FetchProductByID(IProductController productController, int id) 
    { 
     return productController.GetByID(id); 
    } 

    // option 3: black box the whole thing, this is more of a servicelocator pattern 
    public static Product FetchProductsByID(string controllerName, int id) 
    { 
     var productController = getProductController(controllerName); 
     return productController.GetByID(id); 
    } 

    private static IProductController getProductController(string controllerName) 
    { 
     // hard code them or use configuration data or reflection 
     // can also make this method non static and abstract to create an abstract factory 
     switch(controllerName.ToLower()) 
     { 
      case "someproductcontroller": 
       return new SomeProductController(); 
      case "anotherproductcontroller": 
       // etc 

      default: 
       throw new NotImplementedException(); 
     } 
    } 
} 

これは、すべての種類のProductControllerの実装が使用する必要が選択するための責任を負うことになるだろう誰に依存。

+0

この状況では、Dependency Injection(Inversion of Control)が本当に便利です。上記のように、実行時にProductControllerの動作を変更することができます。 – Jens

+0

ありがとう、私はいくつかの種類のDIフレームワークを使用して見てきました。 – Simon

関連する問題