Break dependency on DateTime
In Utilities, add Clock.cs
.
csharp
public interface IClock
{
DateTime UtcNow { get; }
DateTime Now { get; }
}
public class Clock : IClock
{
private readonly TimeZoneInfo _timeZoneInfo;
public Clock(IConfiguration configuration)
{
var timeZoneName = configuration.Get<AppSettings>().Timezone;
_timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName);
}
public DateTime UtcNow => DateTime.UtcNow;
public DateTime Now => TimeZoneInfo.ConvertTime(DateTime.UtcNow, _timeZoneInfo);
}
Back in BookService, inject IClock
and use _clock.Now.Year
instead.
csharp
public class BookService(ILogger<BookService> logger, IClock clock) : IBookService
{
public int Create(CreateBookRequest request)
{
logger.LogInformation("BookController.Create - Request {@request}", request);
if (request.PublicationYear < 1900 || request.PublicationYear > clock.Now.Year)
{
throw new ValidationException("Publication Year must be between 1990 and 2025");
}
//TODO create book
var id = 1;
logger.LogInformation("BookController.Index - Response {@response}", id);
return id;
}
}