Frage

from searching a solution to my circular reference problem between two projects, I came across this:

You can have A depend on B. For simplicity lets say A.EXE depends on B.DLL. Then when A initially calls B, it can give it an object of some type or interface that is defined in B and then B can turn around and call back into A at some later point.

In other words, B defines a base class or interface like "I want something that only A can do" but don't implement it. Then let A implements it, passes it to you, and calls it. This gets around the circular dependency without a third project. This applies to any pair of managed projects.

I tried implementing what was said, but I don't seem to get it right. So my question is, could someone provide me a code example on how to achieve this (VB.Net preferably, C# will do) ?

For reference the original question is here: Solving circular project dependency between C# and C++/CLI projects?

War es hilfreich?

Lösung

Just a minor nitpick. This isn't a real circular dependency, as the idea that "this is something only A could do" is faulty. All B really knows is that "this is something that only someone else can do". It may be true that only A can do it, but that isn't known to B.

Anyhow, a simple example would be this:

In assembly B:

public interface ISomething
{
    void PerformAction();
}

public class ActionManager
{
    public void DoSomething(ISomething something)
    {
        something.PerformAction();
    }
}

In assembly A (which references B):

public class ActionPerformer : ISomething
{
    public void PerformAction()
    {
        ...
    }
}

public class Program
{
    public static void Main()
    {
        ActionManager manager = new ActionManager();
        ActionPerformer performer = new ActionPerformer();

        manager.DoSomething(performer);
    }
}

In short, this example demonstrates code that (after full polymorphic resolution) has A call into B, then B calling back into A.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top