[英]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.