In c# I want to write extension methods for the DateTime struct to calculate date differences in years, month, etc.
For being prepared to change the calculation of the date differences I made an interface for this an passed it to a configuration method in the static extension class.
In concrete:
public static class DateTimeExtension
{
private static IDateTimeDifference _dateDifference;
public static void Configure(IDateTimeDifference dateDifference )
{
DateTimeExtension._dateDifference = dateDifference;
}
public static int DiffFromInYears(this DateTime dateFromIncl, DateTime dateToExcl)
{
return _dateDifference.InYears(dateFromIncl, dateToExcl);
}
public static int DiffToInYears(this DateTime dateToExcl, DateTime dateFromIncl)
{
return _dateDifference.InYears(dateFromIncl, dateToExcl);
}
}
My configuration of the services looks like this:
var host = Host
.CreateDefaultBuilder()
.ConfigureServices(
(context, services) =>
{
services.AddSingleton<IDateTimeDifference>( s => new DateDifferenceFullPeriods() );
}
)
.Build();
DateTimeExtension.Configure( host.Services.GetRequiredService<IDateTimeDifference>() );
I want to get as low performance penalties as possible.
Is there a way to enforce the user of my extension methods to call the Configure method at startup?
Would this code be considered testable? How do I test the extension methods? Is it enough to test the implementations of IDateTimeDifference interface?
In general are extension methods a good approach for this problem, considered I don't want to pass a IDateTimeDifference parameter in each difference calculation method.
Are there other methods of injection more suitable? Is dependency injection even necessary, if I don't need to change the difference calculation at run time?