Reputation: 3320
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();
}
}
Upvotes: 1
Views: 481
Reputation: 7356
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 StateMonitorFactory
into the MathController
, instead of the StateMonitor
itself. The factory would then build the StateMonitor
. So the MathController might look like:
public MathController(StateMonitorFactory fact)
{
_stateMonitor = fact.CreateStateMonitor(RefreshMath);
_stateMonitor.Monitor();
}
A third option would be to have the StateMonitor
have an initialization method. In that case the StateMonitor
constructor would become parameterless, but you'd add another method to it with a signature like Start(Action command)
, and MathController
would be responsible for calling that.
Upvotes: 2