繁体   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