Using ITimeProvider
we were forced to take it into special shared common project that must be referenced from the rest of other projects. But this complicated the control of dependencies.
We searched for the ITimeProvider
in the .NET framework. We searched for the NuGet package, and found one that can't work with DateTimeOffset
.
So we came up with our own solution, which depends only on the types of the standard library. We're using an instance of Func<DateTimeOffset>
.
public class ThingThatNeedsTimeProvider
{
private readonly Func<DateTimeOffset> now;
private int nextId;
public ThingThatNeedsTimeProvider(Func<DateTimeOffset> now)
{
this.now = now;
this.nextId = 1;
}
public (int Id, DateTimeOffset CreatedAt) MakeIllustratingTuple()
{
return (nextId++, now());
}
}
Autofac
builder.RegisterInstance<Func<DateTimeOffset>>(() => DateTimeOffset.Now);
(For future editors: append your cases here).
public void MakeIllustratingTuple_WhenCalled_FillsCreatedAt()
{
DateTimeOffset expected = CreateRandomDateTimeOffset();
DateTimeOffset StubNow() => expected;
var thing = new ThingThatNeedsTimeProvider(StubNow);
var (_, actual) = thing.MakeIllustratingTuple();
Assert.AreEqual(expected, actual);
}