属性 使用 autofac 注入扩展 class

property injection into extension class with autofac

我想使用 属性 注入将我的 class(IDateTimeService ) 注入到扩展 class 中:

public  static  class DateTimeGetter
{

    public static  IDateTimeService Localdate { set; get; }

    public async  static Task<DateTime> FromService(this DateTime value)
    {
        //ocaldate = localdate;
        return await Localdate.Get();
    }
}

我已经使用 restease 使用接口连接到另一个微服务,如您所见:

public interface IDateTimeService
    {
        [AllowAnyStatusCode]
        [Get("api/LocalTime")]
        Task<DateTime> Get();
    }

最后我将注入代码添加到我的启动文件中:

      builder.RegisterType<IDateTimeService>();

问题是当我 运行 我的服务 Localdate 属性 为空时 :

防止将 易失性依赖项 存储到静态字段中,因为这会导致 Ambient Context anti-pattern:

An Ambient Context supplies application code outside the Composition Root with global access to a Volatile Dependency or its behavior by the use of static class members.

一个易失性依赖是:

a Dependency that involves side effects that can be undesirable at times. This may include modules that don’t yet exist or that have adverse requirements on its runtime environment. These are the Dependencies that are addressed by DI and hidden behind Abstractions.

相反,有几种解决方案:

  • 使用 方法注入 IDateTimeService 注入到静态 FromService 方法中。 (见示例 1)
  • DateTimeGetter 提升为实例 class 并注入 IDateTimeService 使用 构造函数注入DateTimeGetter的构造函数中。 (见示例 2)

示例 1:

public static class DateTimeGetter
{
    public async static Task<DateTime> FromService(
        this DateTime value, IDataTimeService timeProvider)
    {
        return await timeProvider.Get();
    }
}

示例 2:

public class DateTimeGetter : IDateTimeGetter
{
    private readonly IDataTimeService timeProvider;

    public DateTimeGetter(IDataTimeService timeProvider)
    {
        this.timeProvider = timeProvider ?? throw new ArgumentNullException("timeProvider");
    }

    public async Task<DateTime> FromService(
        DateTime value, IDataTimeService timeProvider)
    {
        return await this.timeProvider.Get();
    }
}

使用构造函数注入时,DateTimeGetter 本身必须注入其消费者。