This repository was archived by the owner on Jan 20, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Using TimeServices with Dependency Injection
hatchan edited this page Mar 28, 2011
·
3 revisions
TimeServices was created with Dependency Injection in mind, whether you use Poor Man's Dependency Injection or you use a Dependency Injection Container.
When you create new classes which access to time, then make sure you you depend on a IClock. This way you can always switch implementation.
A example using constructor injection:
public class UserService
{
private readonly IClock _clock;
public UserService(IClock clock)
{
_clock = clock;
}
public User CreateNewUser(string name)
{
return new User
{
Name = name,
CreationDate = _clock.Now
};
}
}Another example, but this time using property injection with the SystemClock as default (so it will still work, if nothing gets injected):
public class UserService
{
private IClock _clock = SystemClock.Instance;
public IClock Clock
{
get { return _clock; }
set { _clock = value; }
}
public User CreateNewUser(string name)
{
return new User
{
Name = name,
CreationDate = Clock.Now
};
}
}