我之前通过两种方式解耦了这种情况:状态变化和日志事件。
第一种方法是创建一个 IHaveStatus 接口,如下所示:
/// <summary>
/// Interface for objects that have a status message
/// that describes their current state.
/// </summary>
public interface IHaveStatus
{
/// <summary>
/// Occurs when the <seealso cref="Status"/> property has changed.
/// </summary>
event EventHandler<StatusChangedEventArgs> StatusChanged;
/// <summary>
/// The current status of the object. When this changes,
/// <seealso cref="StatusChanged"/> fires.
/// </summary>
string Status { get; }
}
当你的对象做事时,你设置你的 Status 属性。您可以将属性设置器配置为在设置时触发 StatusChanged 事件。使用您的对象的任何人都可以侦听您的状态更改事件并记录发生的所有事情。
另一个版本是向您的对象添加日志事件。
public event EventHandler<LogEventArgs> Log;
主体几乎相同,只是您的对象比状态驱动的日志更健谈(只有在您特别想记录某些内容时才会触发该事件)。
这个想法是 DAL 之外的调用者有责任将这些事件连接到正确的日志(希望通过使用 DI 设置)。您的 DAL 不知道是谁或什么在消耗这些事件,从而很好地区分了这些问题。