比方说,我有我通过EF加载Patient
和Cycle
域实体:自定义实体 - 视图模型映射器循环依赖
public class Patient
{
public int PatientId { get; set; }
public string Name { get; set; }
public List<Cycle> Cycles { get; set; }
public Patient()
{
Cycles = new List<Cycle>();
}
}
public class Cycle
{
public int CycleId { get; set; }
public int PatientId { get; set; }
public bool IsActive { get; set; }
public Patient Patient { get; set; }
}
正如你所看到的,Patient
拥有的Cycles
集合的导航属性和Cycles
有一个导航属性参考返回到Patient
。
以前,我使用过AutoMapper,但想完全控制我的域实体 - 视图模型映射,所以我创建了自定义映射器。这里是一个Patient
:
public class PatientMapper : IPatientMapper
{
private readonly ICycleMapper cycleMapper;
public PatientMapper(ICycleMapper cycleMapper)
{
this.cycleMapper= cycleMapper;
}
public PatientViewModel GetViewModel(Patient patient)
{
if (patient == null)
{
return null;
}
var viewModel = new PatientViewModel();
viewModel.PatientId = patient.PatientId;
viewModel.Name = patient.Name;
viewModel.Cycles = patient.Cycles.Select(x => cycleMapper.GetViewModel(x)).ToList();
return viewModel;
}
}
正如你所看到的,我需要注入CycleMapper
。在CycleMapper
中,我需要注入一个PatientMapper
实例来映射Patient
导航属性。这会导致循环DI问题。
我已经通过创建每个实体的“基本”版本解决了这个问题。例如,BasicCycle
将不具有Patient
导航属性。这个工作,但需要更多的实体,映射器等。
有没有更好的方法?
而不是注入实例 - 注入工厂('Func'或自定义工厂)。 –
Evk
@Evk感谢您的回复。我没有完全掌握。你可以发布一个kopy.io吗? – im1dermike
您是否需要与其绑定的患者以外的“周期”?如果没有,那么为什么不用CycleMapper.GetViewModel(patient)来更改CycleMapper中的GetViewModel定义。根据我的理解,您的周期只需要一个患者实例来填充它的Patient导航属性。 – Alaminut