how to register NodaTime.ZonedClock with Autofac

Viewed 149

It is possible to register NodaTime.SystemClock like this: builder.Register(_ => SystemClock.Instance).As<IClock>().SingleInstance();, according to Pac0's comment here.

How do I do the same for NodaTime.ZonedClock?

1 Answers

ZonedClock doesn't seem to have any singleton accessor like SystemClock does, so you have to call it's constructor. Using the same approach you used for SystemClock, it would look something like this:

builder
    .Register(_ => new ZonedClock(SystemClock.Instance, DateTimeZone.Utc, CalendarSystem.Gregorian))
    .As<IClock>()
    .SingleInstance();

You can adapt the parameters as you see fit (I added DateTimeZone.Utc and CalendarSystem.Gregorian as examples).

Keep in mind that, since both implement the same interface (IClock) you can't register both at the same time without using keyed registrations or something similar. If you just want to use the ZonedClock however, this should not be a problem.

Related