[英]How do I perform a dependency injection to configure extension methods in c#?
In c# I want to write extension methods for the DateTime struct to calculate date differences in years, month, etc.在 c# 中,我想为 DateTime 结构编写扩展方法来计算年、月等的日期差异。
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.为了准备更改日期差异的计算,我为此创建了一个接口,并将其传递给 static 扩展 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?有没有办法强制我的扩展方法的用户在启动时调用 Configure 方法?
Would this code be considered testable?这段代码会被认为是可测试的吗? How do I test the extension methods?如何测试扩展方法? Is it enough to test the implementations of IDateTimeDifference interface?测试 IDateTimeDifference 接口的实现是否足够?
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.一般来说,扩展方法是解决这个问题的好方法,考虑到我不想在每个差异计算方法中传递 IDateTimeDifference 参数。
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?如果我不需要在运行时更改差异计算,是否需要依赖注入?
TimeSpan
struct https://docs.microsoft.com/en-us/dotnet/api/system.timespan?view=net-5.0 to calculate time differences in days, months, years?您不能只使用TimeSpan
结构https://docs.microsoft.com/en-us/dotnet/api/system.timespan?view=net-5.0来计算天、月、年的时间差吗?this
object.扩展方法必须只依赖于它们的参数和this
object。 They should not have any other external dependency.他们不应该有任何其他的外部依赖。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.