DI在哪里适合CQS?

时间:2011-07-14 19:01:39

标签: dependency-injection command

每当命令需要依赖时,您是否必须求助于属性注入?

说我有以下命令。

public class AddReviewCommand
{
    private ISession _session;
    private readonly string _reviewSummary;

    public AddReviewCommand(string reviewSummary)
    {
        _reviewSummary = reviewSummary;
    }

    public void Execute()
    {
        var review = new Review
            {
                AddedBy = Environment.Username,
                AddedDateTime = DateTime.Now,
                ReviewSummary = _reviewSummary
            };

            _session.Save(review);
    }
}

注入ISession的唯一方法是通过属性注入吗?

1 个答案:

答案 0 :(得分:2)

属性注入意味着依赖项是可选,这很少是正确的不变量。 构造函数注入是一个更合适的模式:

public class AddReviewCommand
{
    private ISession _session;
    private readonly string _reviewSummary;

    public AddReviewCommand(string reviewSummary, ISession session)
    {
        _reviewSummary = reviewSummary;
        _session = session;
    }

    public void Execute()
    {
        var review = new Review
        {
            AddedBy = Environment.Username,
            AddedDateTime = DateTime.Now,
            ReviewSummary = _reviewSummary
        };

        _session.Save(review);
    }
}