比方說,我們有構造函數注射和默認的重載
public interface ITimestampProvider
{
DateTime GetTimestamp();
}
和消耗它
public class Timestamped
{
private ITimestampProvider _timestampProvider
public Timestamped(ITimestampProvider timestampProvider)
{
// arg null check
_timestampProvider = timestampProvider;
}
public DateTime Timestamp { get; private set; }
public void Stamp()
{
this.Timestamp = _timestampProvider.GetTimestamp();
}
}
和的默認實現類:
public sealed class SystemTimestampProvider : ITimestampProvider
{
public DateTime GetTimestamp()
{
return DateTime.Now;
}
}
它是有益還是harfmful介紹這個構造函數?
public Timestamped() : this(new SystemTimestampProvider())
{}
這是一個普遍的問題,即時間戳不是有趣的部分。
CAB使用什麼樣的依賴注入風格?城堡? – 2008-11-18 22:00:52
就這個問題而言,沒有。這是一個通用的API查詢。我已經更新了這個問題,以消除「注入」的內涵。 – 2008-11-18 22:09:34