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);
}
}
精彩评论