15

例:

public abstract class BaseControler : Controller
{
    public IUnitOfWork UnitOfWork { get; set; }
}

public class HomeController : BaseControler
{
    readonly IUserRepository _userRepository;

    // :-)
    public HomeController(IUserRepository userRepository)
    {
        _userRepository = userRepository;
    }
}

依存関係が必要な場合、コンストラクター インジェクションを使用する必要があることは誰もが知っています。オプションの依存関係である場合は、代わりにプロパティ インジェクションを使用できます。

しかし、基本クラスだけが依存関係を必要とする場合はどうすればよいでしょうか?

コンストラクター インジェクションを使用すると、私の意見では、すべての派生クラスが汚染されます。

public abstract class BaseControler : Controller
{
    readonly IUnitOfWork _unitOfWork;

    public BaseControler(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }
}

public class HomeController : BaseControler
{
    readonly IUserRepository _userRepository;

    // :-(
    public HomeController(IUserRepository userRepository, 
       IUnitOfWork unitOfWork) : base(unitOfWork)
    {
        _userRepository = userRepository;
    }
}

基本クラスでのみ依存関係が必要な場合、基本クラスでプロパティ注入を使用するのは適切ですか?

4

2 に答える 2

16

You are not polluting the derived class. You are explicitly stating to the consumer that this class cannot function without this dependency.

If the base class requires this dependency in order to function properly, since the derived class derives from this base class, it implicitly requires this dependency as well. So the second example is the correct way. You shouldn't be using property injection for something that is a required dependency.

于 2012-05-04T13:29:31.580 に答える
3

実際、派生クラスは基本クラスです。どこかに他のオブジェクトはありません。基本コンストラクターに何かを渡すと、実際には同じオブジェクトを初期化します。そして、インスタンスが何に依存しているかをクライアントに示します。

public HomeController(IUserRepository userRepository, IUnitOfWork unitOfWork)

ユーザー・リポジトリーと作業単位の 2 つに依存する 1 つのインスタンスがあります。基本クラスのコンストラクターを呼び出すと、派生クラスから初期化の重複が削除されるだけです。

于 2012-05-04T13:39:57.983 に答える