我对洋葱建筑有点新鲜。我创建了一个服务层,通过手动将它们传递给构造函数来调用DAL中的存储库。但现在看我的方法我正在使用核心域中的对象,我想知道我是否应该通过接口访问它?是否应通过参数,构造函数,属性等传入的接口访问所有对象?我知道这会使它更少耦合,但就最佳实践而言,这是什么?
在我的代码中,我想知道是否
DiaryEvent diaryEvent = new DiaryEvent();
应该用作接口而不是具体对象。附: DiaryEvent来自下面的层(核心)。
public class DiaryEventService : IDiaryEventService
{
private readonly IYogaSpaceEventRepository yogaSpaceEventRepository;
public DiaryEventService() : this(new YogaSpaceEventRepository())
{
}
public DiaryEventService(IYogaSpaceEventRepository yogaSpaceEventRepository)
{
this.yogaSpaceEventRepository = yogaSpaceEventRepository;
}
public List<DiaryEvent> LoadAllAppointmentsInDateRange(double start, double end)
{
var fromDate = ConvertFromUnixTimestamp(start);
var toDate = ConvertFromUnixTimestamp(end);
var yogaSpaceEvents = yogaSpaceEventRepository.Find(fromDate, toDate);
List<DiaryEvent> result = new List<DiaryEvent>();
foreach (var item in yogaSpaceEvents)
{
DiaryEvent diaryEvent = new DiaryEvent();
diaryEvent.ID = item.YogaSpaceEventId;
//diaryEvent.SomeImportantKeyID = item.SomeImportantKey;
diaryEvent.StartDateString = item.DateTimeScheduled.ToString("s");
// "s" is a preset format that outputs as: "2009-02-27T12:12:22"
diaryEvent.EndDateString = item.DateTimeScheduled.AddMinutes(item.AppointmentLength).ToString("s");
// field AppointmentLength is in minutes
diaryEvent.Title = item.Title + " - " + item.AppointmentLength.ToString() + " mins";
diaryEvent.StatusString = Enums.GetName<AppointmentStatus>((AppointmentStatus)item.StatusEnum);
diaryEvent.StatusColor = Enums.GetEnumDescription<AppointmentStatus>(diaryEvent.StatusString);
string ColorCode = diaryEvent.StatusColor.Substring(0, diaryEvent.StatusColor.IndexOf(":"));
diaryEvent.ClassName = diaryEvent.StatusColor.Substring(diaryEvent.StatusColor.IndexOf(":") + 1,
diaryEvent.StatusColor.Length - ColorCode.Length - 1);
diaryEvent.StatusColor = ColorCode;
result.Add(diaryEvent);
}
return result;
}
private static DateTime ConvertFromUnixTimestamp(double timestamp)
{
var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return origin.AddSeconds(timestamp);
}
}
答案 0 :(得分:0)
但现在看着我的方法,我正在使用核心域中的对象 我想知道我是否应该通过接口访问它 还有吗?
查看上面的代码,看起来你做得对。 DiaryEvent看起来像一个结构,即没有行为的数据对象,因此不需要用接口替换它。接口输出对象有助于在运行时和这里注入它们,因为你没有调用任何行为,即DiaryEvent的方法,可以直接将它们实例化到方法中。
不,不是真的。可以这样想,如果从类中调用方法,则该类依赖于调用的方法/类的行为。为了使它松散耦合,即在运行时更改行为/模拟它,您将需要注入此依赖项。要从外部注入依赖项,您需要接口或抽象依赖项。是否应通过传入的接口访问所有对象 参数,构造函数,属性等??
验证类是否松散耦合的一种好方法是为其模拟依赖项的方法编写一个单元测试用例。