Skip to content

Instantly share code, notes, and snippets.

@dennisroche
Last active December 9, 2017 14:11
Show Gist options
  • Save dennisroche/4b60ec1a8aa6e2debfa0fa2da904a95f to your computer and use it in GitHub Desktop.
Save dennisroche/4b60ec1a8aa6e2debfa0fa2da904a95f to your computer and use it in GitHub Desktop.
NodaTime Static Clock
public static class NodaClock
{
private static readonly AsyncLocal<IClock> ClockThreadSafe;
public static void ChangeClock(IClock clock)
{
ClockThreadSafe.Value = clock;
}
static ApiClock()
{
ClockThreadSafe = new AsyncLocal<IClock>();
}
public static IClock Clock => ClockThreadSafe.Value ?? SystemClock.Instance;
public static Instant Now => Clock.GetCurrentInstant();
}
public class OverrideNodaClock : IDisposable
{
private OverrideNodaClock(FakeClock fakeClock)
{
_fakeClock = fakeClock;
_clock = NodaClock.Clock;
NodaClock.ChangeClock(_fakeClock);
}
public OverrideApiClock(Instant instant)
: this(new FakeClock(instant))
{
}
public void Dispose()
{
ApiClock.ChangeClock(_clock);
}
public OverrideApiClock Reset(Instant instant)
{
_fakeClock.Reset(instant);
return this;
}
public OverrideApiClock Advance(Duration duration)
{
_fakeClock.Advance(duration);
return this;
}
private readonly IClock _clock;
private readonly FakeClock _fakeClock;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment