Inject IDateTime to remove the hard dependency against the DateTime class. This makes it easier to decouple and test your code by making your use of DateTime mockable or providing your own implementation.
Install the IDateTime NuGet package:
dotnet add package IDateTime
First, add it to your IoC container:
services.AddIDateTime();
Inject IDateTime
into your class:
public class ExampleService
{
private readonly IDateTime _dateTime;
public ExampleService(IDateTime dateTime)
{
_dateTime = dateTime;
}
public DateTime WhenWasYesterday()
{
return _dateTime.UtcNow().AddDays(-1);
}
}
Ping me if you want any new features added to the library ❤️