July 12, 2024

Time Providers

In .Net 8.0 there is now a means to inject a time provider. Here is a link https://blog.nimblepros.com/blogs/finally-an-abstraction-for-time-in-net/


1. It can be passed via dependency injection:
ServiceCollection services = new ServiceCollection();
...
services.AddSingleton<TimeProvider>(TimeProvider.System);

2. Pass it in to your constructor
private readonly TimeProvider _timeProvider;
public MyConstructor(..., TimeProvider timeProvider)
{
    _timeProvider = timeProvider;
}

3. Use it somewhere
void SomeMethod()
{
…
   var nowUtc = _timeProvider.GetUtcNow();
…
}

4. Use the FakeTimeProvider in unit tests
using Microsoft.Extensions.Time.Testing; // Get from Package from NuGet (same name as namespace)
...
FakeTimeProvider fakeTimeProvider = new();
fakeTimeProvider.SetUtcNow(new DateTimeOffset(2025, 3, 4, 13, 22, 42, new TimeSpan(0)));
...
fakeTimeProvider.Advance(new TimeSpan(entry.TimeMs * TimeSpan.TicksPerMillisecond));

No comments: