I have a situation here, where by I need a timer in my class which invokes some method based on time interval.
On normal scenarios I would have instantiated timer and configured it in the constructor itself. But I want to do it in dependency injection style. Passing the timer in the constructor is easy, but in order to bind a method to its OnTimeElapsed is tricky, should the factory instantiating the class, configure this timer? how should I go ahead without violating dpendency injection principles.
Thanks
Edit1
Ok, let me rephrase what I actually wanted to ask.My main goal of achieving dependency injection is that I need to unit test that on a particular elapsed time whether a method has been called or not.
So my question is: where should I bind OnTimerElapsed event? Am I actually trying to test the timer here? I seem to get lost here
kindly help.
If your question is, that you want to dependency inject a timer that you can later bind an event to, it should be simple.
Just create your Timer
class to follow an ITimer
interface and create methods on it to do the actions you want.
public class Calendar
{
public Calendar(ITimer timer)
{
// timer is the dependency injected timer
timer.SetEvent(EventReminder, 3600);
}
public void EventReminder()
{
Console.Write("Hey, it's time for your appointment!");
}
}
public interface ITimer
{
void SetEvent(Action callbackMethod, int interval);
}
In this case, you have a calendar application, and you want your application to have a timer. But you don't care how the timer works, or even what kind of timer (maybe you want a timer that works on minutes, or hours, or it works some other way). All you know is that you want a timer, so you dependency inject one.
You have to create an interface, that defines what the timer will do, because although it doesn't care about which timer you use, it does care about the capabilities of the timer. In our case, the timer can do one thing - set an event to occur after a certain interval.
So we inject the timer, but in order to be able to use it, or set it up, we use the interface to define methods. We never know how it works internally - we don't even know it has an OnElapsedEvent, and we don't care. Leave that to the creator of the timer, we just want one method that will do the task, and that's what the code above demonstrates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With