开发者

Where does DI fit in with CQS?

开发者 https://www.devze.com 2023-03-20 04:52 出处:网络
Must you resort to property injection whenever a command requires a dependency? Say I have the following command.

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

精彩评论

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