我正在寻找避免构造函数注入过度使用的最佳实践。例如,我有会议实体,它有几个子实体,如下所示:
- 会议
- 会议联系人
- 会议与会者
- 会议类型
- 地址
- 会议公司
- 会议记录
MeetingService 类如下所示:
public class MeetingService
{
private readonly IMeetingContactRepository _meetingContactRepository;
private readonly IMeetingAttendeeRepository _meetingAttendeeRepository;
private readonly IMeetingTypeRepository _meetingTypeRepository;
private readonly IAddressRepository _addressRepository;
private readonly IMeetingCompanyRepository _meetingCompanyRepository;
private readonly IMeetingNoteRepository _meetingNoteRepository;
private readonly IMeetingRepositoy _meetingReposity;
public MeetingService(IMeetingRepositoy meetingReposity, IMeetingContactRepository meetingContactRepository, IMeetingAttendeeRepository meetingAttendeeRepository,
IMeetingTypeRepository meetingTypeRepository, IAddressRepository addressRepository,
IMeetingCompanyRepository meetingCompanyRepository, IMeetingNoteRepository meetingNoteRepository)
{
_meetingReposity = meetingReposity;
_meetingContactRepository = meetingContactRepository;
_meetingAttendeeRepository = meetingAttendeeRepository;
_meetingTypeRepository = meetingTypeRepository;
_addressRepository = addressRepository;
_meetingCompanyRepository = meetingCompanyRepository;
_meetingNoteRepository = meetingNoteRepository;
}
public void SaveMeeting(Meeting meeting)
{
meetingReposity.Save();
if(Condition1())
_meetingContactRepository.Save();
if(Condition2())
_meetingAttendeeRepository.Save();
if(Condition3())
_meetingTypeRepository.Save();
if(Condition4())
_addressRepository.Save();
if(Condition5())
_meetingCompanyRepository.Save();
if(Condition6())
_meetingNoteRepository.Save();
}
//... other methods
}
这里只是七个依赖项,但实际代码包含更多。我使用了“依赖注入构造函数疯狂”中描述的不同技术,但我还没有找到如何处理存储库依赖关系。
有什么办法可以减少依赖项的数量并保持代码可测试?