5

私は DI の初心者なので、これが間違ったアプローチやばかげた質問である場合はご容赦ください。

注文を作成/更新するフォームがあり、表示する製品と顧客のリストを取得する必要があることがわかっているとします。編集中の Order オブジェクトを渡したいのですが、依存関係として ProductsService と CustomersService も注入したいと考えています。

そのため、IoC コンテナー (どちらを使用する場合でも) でサービスを提供する必要がありますが、編集する Order オブジェクトを提供するのは呼び出し元のコード次第です。

Order オブジェクトを最初のパラメーターとして受け取り、その後に ProductsService と CustomersService を受け取るようにコンストラクターを宣言する必要があります。

public OrderForm(Order order, ProductsService prodsSvc, CustomersService custsSvc)

...または、依存関係が最初に来て、 Order オブジェクトが最後に来る必要があります。例:

public OrderForm(ProductsService prodsSvc, CustomersService custsSvc, Order order)

それは問題ですか?使用する IoC コンテナーに依存しますか? それとも「より良い」方法はありますか?

4

4 に答える 4

5

マット、通常のパラメーターと依存関係を混在させるべきではありません。オブジェクトは IoC コンテナーの内部で作成されるため、必要な引数をどのように指定しますか?

依存関係と通常の引数を混在させると、プログラムのロジックがより複雑になります。

この場合、依存関係プロパティを宣言する (つまり、コンストラクターから依存関係を削除する) か、IoC がOrderFormを構築してその依存関係を解決した後に注文フィールドを初期化する(つまり、コンストラクターから通常のパラメーターを削除する) 方がよいでしょう。

また、依存関係として順序を含むすべてのパラメーターを宣言することもできます。

于 2008-10-01T05:08:14.423 に答える
4

I disagree with @aku's answer.

I think what you're doing is fine and there are also other ways to do it that are no more or less right. For instance, one may question whether this object should be depending on services in the first place.

Regardless of DI, I feel it is helpful to clarify in your mind at least the kind of state each object holds, such as the real state (Order), derived state (if any), and dependencies (services):

http://tech.puredanger.com/2007/09/18/spelunking/

On any constructor or method, I prefer the real data to be passed first and dependencies or external stuff to be passed last. So in your example I'd prefer the first.

于 2008-10-01T06:05:17.393 に答える
3

I feel a bit uneasy about allowing an instance of OrderForm to be instantiated without the required reference to an Order instance. One reason might be that this would prevent me from doing upfront checking for null orders. Any further thoughts?

I suppose I could take some comfort in knowing that OrderForm objects will only be instantiated by a Factory method that ensures the Order property is set after making the call to the IoC framework.

于 2008-10-01T05:53:38.683 に答える