Last active
December 9, 2017 14:11
-
-
Save dennisroche/4b60ec1a8aa6e2debfa0fa2da904a95f to your computer and use it in GitHub Desktop.
NodaTime Static Clock
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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