Proper way to inject NodaTime.IClock
Nov 26, 2022
It seems like a pretty straightforward task to inject dependency, but I struggled some time with it. So, to do it using Microsoft DI (ServiceProvider, ServiceCollection…) use:
services.AddSingleton<IClock>(SystemClock.Instance);
Autofac (with builder
as ContainerBuilder
) :
builder.Register(_ => SystemClock.Instance).As<IClock>().SingleInstance();
NInject :
container.Bind<IClock>().ToConstant(SystemClock.Instance);
At last — Unit tests the injection of FakeClock:
services.AddSingleton<IClock>(FakeClock.FromUtc(2022, 12, 1));