I have a class (MathController) that knows how to refresh a Math component.
That class uses a helper class for determining when to trigger the refresh, based on a time schedule.
What I’d like to do is to add the helper class to my IoC container.
Currently, the IoC creates the MathController. Since the helper class needs to receive an Action from the MathController, I don’t know how to do that without getting into a circular dependencies scenario.
This is a sample I’ve created as an example of the scenario.
void Main()
{
var mathController = new MathController();
}
class MathController
{
private readonly StateMonitor _stateMonitor;
public MathController()
{
_stateMonitor = new StateMonitor(RefreshMath);
_stateMonitor.Monitor();
}
public void RefreshMath()
{
Debug.WriteLine("Math has been refreshed");
}
}
class StateMonitor
{
private readonly Action _refreshCommand;
public StateMonitor(Action command)
{
_refreshCommand = command;
}
public void Monitor()
{
Debug.WriteLine("Start monitoring");
Thread.Sleep(5000);
Debug.WriteLine("Something happened, we should execute the given command");
_refreshCommand();
}
}
Your IoC container may support some way to do this. For instance, NInject allows you to register a provider (basically a factory method) which could handle the initialization for you. It might help if you said which IoC container & version you’re using.
Another way would be to inject a
StateMonitorFactoryinto theMathController, instead of theStateMonitoritself. The factory would then build theStateMonitor. So the MathController might look like:A third option would be to have the
StateMonitorhave an initialization method. In that case theStateMonitorconstructor would become parameterless, but you’d add another method to it with a signature likeStart(Action command), andMathControllerwould be responsible for calling that.