依存性注入は良いことのようです。一般に、依存関係は、依存関係を必要とするメソッドに注入する必要がありますか、それともクラスのコンストラクターに注入する必要がありますか?
同じ依存関係を注入する2つの方法を示すには、以下のサンプルを参照してください。
//Inject the dependency into the methods that require ImportantClass
Class Something {
public Something()
{
//empty
}
public void A()
{
//do something without x
}
public void B(ImportantClass x)
{
//do something with x
}
public void C(ImportantClass x)
{
//do something with x
}
}
//Inject the dependency into the constructor once
Class Something {
private ImportantClass _x
public Something(ImportantClass x)
{
this._x = x;
}
public void A()
{
//do something without x
}
public void B()
{
//do something with this._x
}
public void C()
{
//do something with this._x
}
}