Frage

The title says "Circular Dependency", but it is not the correct wording, because to me the design seems solid.
However, consider the following scenario, where the blue parts are given from external partner, and orange is my own implementation. Also assume there is more then one ConcreteMain, but I want to use a specific one. (In reality, each class has some more dependencies, but I tried to simplify it here)

Scenario

I would like to instanciate all of this with Depency Injection (Unity), but I obviously get a StackOverflowException on the following code, because Runner tries to instantiate ConcreteMain, and ConcreteMain needs a Runner.

IUnityContainer ioc = new UnityContainer();
ioc.RegisterType<IMain, ConcreteMain>()
   .RegisterType<IMainCallback, Runner>();
var runner = ioc.Resolve<Runner>();

How can I avouid this? Is there any way to structure this so that I can use it with DI? The scenario I'm doing now is setting everything up manually, but that puts a hard dependency on ConcreteMain in the class which instantiates it. This is what i'm trying to avoid (with Unity registrations in configuration).

All source code below (very simplified example!);

public class Program
{
    public static void Main(string[] args)
    {
        IUnityContainer ioc = new UnityContainer();
        ioc.RegisterType<IMain, ConcreteMain>()
           .RegisterType<IMainCallback, Runner>();
        var runner = ioc.Resolve<Runner>();

        Console.WriteLine("invoking runner...");
        runner.DoSomethingAwesome();

        Console.ReadLine();
    }
}

public class Runner : IMainCallback
{
    private readonly IMain mainServer;

    public Runner(IMain mainServer)
    {
        this.mainServer = mainServer;
    }

    public void DoSomethingAwesome()
    {
        Console.WriteLine("trying to do something awesome");
        mainServer.DoSomething();
    }

    public void SomethingIsDone(object something)
    {
        Console.WriteLine("hey look, something is finally done.");
    }
}

public interface IMain
{
    void DoSomething();
}

public interface IMainCallback
{
    void SomethingIsDone(object something);
}

public abstract class AbstractMain : IMain
{
    protected readonly IMainCallback callback;

    protected AbstractMain(IMainCallback callback)
    {
        this.callback = callback;
    }

    public abstract void DoSomething();
}

public class ConcreteMain : AbstractMain
{
    public ConcreteMain(IMainCallback callback) : base(callback){}

    public override void DoSomething()
    {
        Console.WriteLine("starting to do something...");
        var task = Task.Factory.StartNew(() =>{ Thread.Sleep(5000);/*very long running task*/ });
        task.ContinueWith(t => callback.SomethingIsDone(true));
    }
}
War es hilfreich?

Lösung

What you can do is to create a factory, MainFactory that returns an instance of ConcreteMain as IMain.

Then you can inject this Factory into your Runner constructor. Create the Main with the factory and pass inn itself as a parameter.

Any other dependencies on the ConcreteMain constructor can be passed into the MyMainFactory via IOC and pushed to the concrete constructor manually.

public class MyMainFactory
{
    MyOtherDependency _dependency;

    public MyMainFactory(MyOtherDependency dependency)
    {
        _dependency = dependency;
    }

    public IMain Create(Runner runner)
    {
        return new ConcreteMain(runner, _dependency);
    }
}

public class Runner
{
    IMain _myMain;
    public Runner(MyMainFactory factory)
    {
        _myMain = factory.Create(this)
    }
}

Andere Tipps

Use an IOC container that supports this scenario. I know that AutoFac and possible others does. When using AutoFac the restriction is that one of the dependencies must have PropertiesAutoWired=true and use a Property for the dependency.

Some IOC containers (for example Spring or Weld) can solve this issue using dynamically-generated proxies. Proxies are injected on both ends and the real object is only instantiated when the proxy is first used. That way, circular dependencies aren't an issue unless the two objects call methods on each other in their constructors (which is easy to avoid).

With Unity 3, you can now inject Lazy<T>. This is similar to injecting a Factory/object cache.

Just be sure that you don't do work in your ctor that requires resolving the Lazy dependency.

Lizenziert unter: CC-BY-SA mit Zuschreibung
scroll top