0

I am currently integrating StructureMap within our business layer but have problems because of bidirectional dependencies.

The layer contains multiple managers where each manager can call methods on each other: there are no restrictions or rules for communication. This also includes possible circular dependencies like in the example below. I know the design itself is questionable but currently we just want StructureMap to work and will focus on further refactoring in the future.

Every manager implements the IManager interface:

internal interface IManager
{
  bool IsStarted { get; }

  void Start();
  void Stop();
}

And also has its own specific interface:

internal interface IManagerA : IManager
{
  void ALogic();
}

internal interface IManagerB : IManager
{
  void BLogic();
}

Here are two dummy manager implementations:

internal class ManagerA : IManagerA
{
  public IManagerB ManagerB { get; set; }

  public void ALogic() { }

  public bool IsStarted { get; private set; }
  public void Start() { }
  public void Stop() { }
}

internal class ManagerB : IManagerB
{
  public IManagerA ManagerA { get; set; }

  public void BLogic() { }

  public bool IsStarted { get; private set; }
  public void Start() { }
  public void Stop() { }
}

Here is the StructureMap configuration I use at the moment.

I am still not sure how should I register the managers so currently I am using manual registration. Maybe someone could help me with this too.

For<IManagerA>().Singleton().Use<ManagerA>();
For<IManagerB>().Singleton().Use<ManagerB>();

SetAllProperties(convention =>
{
  // configure the property injection for all managers
  convention.Matching(prop => typeof(IManager).IsAssignableFrom(prop.PropertyType));
});

After all I cannot create IManagerA because StructureMap complains about the circular dependency between ManagerA and ManagerB. Is there an easy and clean solution to solve this problem but to keep the current design?

doppelgreener
  • 4,809
  • 10
  • 46
  • 63
leozilla
  • 1
  • 1
  • 1

1 Answers1

9

Patient: "Doc, it hurts when I poke my finger in my eye"

Doctor: "Stop poking your finger in your eye."

No, there will be no "easy", nor "clean" solution that keeps the current design. When intuition, and your tools, tell you a design isn't working, its probably a good idea to listen.

If something needs an IManagerA, and an IManagerB, then it should take them both as dependencies. A dependency injection tool, like StructureMap, makes these types of composition scenarios easy - don't fight it.

Joshua Flanagan
  • 8,527
  • 2
  • 31
  • 40