2

我有一个项目,我遇到了循环引用问题。Autofac,循环引用和设计解决外键问题

我有一个“事件”对象,我可以有一个“问题”对象列表 我有一个“问题”对象,我可以从中获取父“事件”。

如果我使用实体框架,它将由框架管理,但我有一个要求,不要使用实体框架,出于某种原因,从我的客户。所以,我试图模拟EF的行为,因为我很确定他们最终会感觉到并让我使用EF。下面是我如何进行

public class EventRepository : AbstractRepository<Event>, IEventRepository 
{ 
    private readonly IQuestionRepository questionRepository; 
    public EventRepository(IContext context, IQuestionRepository questionRepository) 
    { 
     this.questionRepository = questionRepository; 
    } 

    public Event GetNew(DataRow row) 
    { 
     return new GeEvent(this.questionRepository) { // Load the event from the datarow } 
    } 

    public class GeEvent : Event 
    { 
     private readonly IQuestionRepository questionRepository; 
     public GeEvent(IQuestionRepository questionRepository) 
     { 
      this.questionRepository = questionRepository; 
     } 
     public override List<Question> Questions { get { return this.questionRepository.GetByIdEvent(this.IdEvent); }} 
    } 
} 

public class QuestionRepository : AbstractRepository<Question>, IQuestionRepository 
{ 
    private readonly IEventRepository eventRepository; 
    public QuestionRepository(IContext context, IEventRepository eventRepository) 
    { 
     this.eventRepository = eventRepository; 
    } 

    public Question GetNew(DataRow row) 
    { 
     return new GeQuestion(this.eventRepository) { // Load the question from the datarow } 
    } 

    public class GeQuestion : Question 
    { 
     private readonly IEventRepository eventRepository; 
     public GeQuestion(IEventRepository eventRepository) 
     { 
      this.eventRepository = eventRepository; 
     } 
     public override Event Event { get { return this.eventRepository.Get(this.IdEvent); }} 
    } 
} 

所以,你可以看到,我有“先有鸡还是先有蛋”的情况。要创建一个EventRepository,它需要一个QuestionRepository并创建一个QuestionRepository,它需要一个EventRepository。除了直接使用DependencyResolver(这会使存储库(和服务)无法正确测试)之外,我如何管理依赖关系,以便可以加载我的外键“一个”实体框架?

顺便说一句,我已简化了外键的“延迟加载”,以保持示例简单。

BTW2我使用Autofac,如果它可以帮助任何事情。

谢谢

回答

0

我可以建议你做你的设计错了吗?在我看来,当涉及到存储库时,你违反了分离关注原则。

问题存储库的工作不是为您提供父对象的Event对象,而仅仅是用户可以从中查询EventRepository以获取事件对象的eventId。同样,对于其他存储库。这样,你不必到处传递的依赖关系,但可以撰写你的要求,如:

var question = _questionRepo.GetNew(row); 
var evnt = _eventRepo.Get(question.IdEvent); 

此外,Autofac不正式支持圆形构造\构造depencies,你可以阅读here

另一种解决方案是将其中一个依赖项更改为属性设置器,然后按照文档中的说明进行操作。

+0

感谢您的回答。我知道,设计并不理想。我通常会使用实体框架,但客户完全反对,因为他说,他的程序员已经有很多东西要学,EF会太过分了......嗯...... EF会照顾所有这些非 - 但是你知道......客户是国王。 我认为我必须去财产二传手,直到客户端来到它的感官,并允许我使用EF。 再次感谢您的答案。 –