mardi 22 juin 2021

How to resolve recursive dependency C#

I have a problem with two interfaces calling each other.
In my model each Component can contain a Grid. And each Grid can contain a Component.
I am trying implement mapper for this model with Dependency Injection.

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);
}

But now I have an error "Recursive dependency detected"
I fixed it when I changed it to static classes, but I think it is dirty hack.

I also tried to use factory for creating an instance for these interfaces in the both methods.
        var container = Current.Factory.Concrete as ServiceContainer;
        var mapper = container.GetInstance<IComponent>();

But it doesn't work too, because each instance of the interface expects an instance of another to come to its constructor.

What pattern should I implement to keep DI in my project?

Aucun commentaire:

Enregistrer un commentaire