首页 > 解决方案 > 如何解决递归依赖C#

问题描述

我有两个接口互相调用的问题。
在我的模型中,每个组件都可以包含一个网格。每个 Grid 都可以包含一个 Component。
我正在尝试使用依赖注入为这个模型实现映射器。

public interface IComponent
{
    //if we found a grid in the content, we should call Map method from IGrid 
    ComponentViewModel Map(IContent content);
}

public interface IGrid
{
    //if we found a component in the content, we should call Map method from IComponent 
    GridViewModel Map(IContent content);
}

但是现在我有一个错误“检测到递归依赖”
,当我将它更改为静态类时我修复了它,但我认为这是肮脏的黑客攻击。

我还尝试使用工厂在这两种方法中为这些接口创建一个实例。
        var container = Current.Factory.Concrete as ServiceContainer;
        var mapper = container.GetInstance<IComponent>();

但它也不起作用,因为接口的每个实例都期望另一个实例进入其构造函数。

我应该实施什么模式来将 DI 保留在我的项目中?

标签: c#.netdesign-patternsdependency-injectionclean-architecture

解决方案


推荐阅读