3

I really like this suggestion on StackOverflow to use an IClock interface to supply your code with the current date/time so you can supply a different date/time when unit testing (not to mention factoring out all of the DateTime.Now references).

I can use dependency injection to supply an implementation of this interface to my service layer.

However, I have alot of DateTime.Now references in my entities (sample below). What is the preferred way of addressing this?

public class SampleEntity
{
  private DateTime someField;
  private DateTime someOtherDate;

  public SampleEntity()
  {
    someField = DateTime.Now;
  }

  public bool SomeProperty
  {
    get { return someOtherDate < DateTime.Now.Date; }
  }

  public bool SomeFunction()
  {
    return SomeOtherDate < DateTime.Now.Date;
  }
}

I can pass in parameters to the function and/or constructor, but that still requires me to explicitly set something if I retrieve the entity from an ORM.

Community
  • 1
  • 1
Mayo
  • 10,544
  • 6
  • 45
  • 90

2 Answers2

2

If you want to use IClock, you will have to replace all DateTime.Now with Clock.Now and have your class take an IClock instance in the constructor:

public class SampleEntity
{
    private DateTime someField;
    private DateTime someOtherDate;
    private readonly IClock _clock;

    public SampleEntity(IClock clock)
    {
        _clock = clock;
        someField = clock.Now;
    }

    public bool SomeProperty
    {
        get { return someOtherDate < _clock.Now.Date; }
    }

    public bool SomeFunction()
    {
        return SomeOtherDate < _clock.Now.Date;
    }
}

As far as passing the concrete implementation of an IClock when instantiating the entity most ORM frameworks provide hooks that could be used to provide custom instances of the entities.

If your ORM doesn't provide such hooks you could still use the accepted answer from the linked question which uses a public static Func<DateTime> Now = () => DateTime.Now; provider.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

If your dependency injection framework has something similar to autowire from spring that would resolve the issue you are having. See Section 4.3.8

Sign
  • 1,919
  • 18
  • 33