开发者

Where does DI fit in with CQS?

Must you resort to property injection whenever a command requires a dependency?

Say I have the following 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 = Dat开发者_运维百科eTime.Now,
                ReviewSummary = _reviewSummary
            };

            _session.Save(review);
    }
}

Is the only way to inject ISession is by property injection?


Property Injection implies that the dependency is optional, which is rarely the correct invariant. Constructor Injection is a much more appropriate pattern:

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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜