每当命令需要依赖时,您是否必须求助于属性注入?
说我有以下命令。
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
的唯一方法是通过属性注入吗?
答案 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);
}
}