簡體   English   中英

如何執行依賴注入來配置 c# 中的擴展方法?

[英]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 參數。

還有其他更適合的注射方法嗎? 如果我不需要在運行時更改差異計算,是否需要依賴注入?

  1. 你真的需要一個擴展方法嗎? 您不能只使用TimeSpan結構https://docs.microsoft.com/en-us/dotnet/api/system.timespan?view=net-5.0來計算天、月、年的時間差嗎?
  2. 擴展方法本質上是 static,它們在 static 類中定義。 另一方面,依賴注入用於注冊 class 的特定實例,並通常通過與其他需要它的類或方法的接口來提供 class 的特定實例。 But since extension methods are defined in static classes and are static you don't need to register an instance of a static class since static classes are loaded automatically when they are required. 一般來說,我看不到任何將依賴注入用於擴展方法的邏輯。 擴展方法必須只依賴於它們的參數和this object。 他們不應該有任何其他的外部依賴。
  3. 有關為結構定義擴展方法的更多信息,您可以在此處閱讀結構上的擴展方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM