[英]How do I perform a dependency injection to configure extension methods in c#?
在 c# 中,我想为 DateTime 结构编写扩展方法来计算年、月等的日期差异。
为了准备更改日期差异的计算,我为此创建了一个接口,并将其传递给 static 扩展 class 中的配置方法。
具体来说:
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);
}
}
我的服务配置如下所示:
var host = Host
.CreateDefaultBuilder()
.ConfigureServices(
(context, services) =>
{
services.AddSingleton<IDateTimeDifference>( s => new DateDifferenceFullPeriods() );
}
)
.Build();
DateTimeExtension.Configure( host.Services.GetRequiredService<IDateTimeDifference>() );
我希望获得尽可能低的性能惩罚。
有没有办法强制我的扩展方法的用户在启动时调用 Configure 方法?
这段代码会被认为是可测试的吗? 如何测试扩展方法? 测试 IDateTimeDifference 接口的实现是否足够?
一般来说,扩展方法是解决这个问题的好方法,考虑到我不想在每个差异计算方法中传递 IDateTimeDifference 参数。
还有其他更适合的注射方法吗? 如果我不需要在运行时更改差异计算,是否需要依赖注入?
TimeSpan
结构https://docs.microsoft.com/en-us/dotnet/api/system.timespan?view=net-5.0来计算天、月、年的时间差吗?this
object。 他们不应该有任何其他的外部依赖。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.