代码之家  ›  专栏  ›  技术社区  ›  Jonathan Wood

通过多个类型使对象从依赖项注入中可用

  •  0
  • Jonathan Wood  · 技术社区  · 1 年前

    我有以下接口和类。

    public interface IWorkingPath
    {
        string WorkingFolder { get; }
    }
    
    public class WorkingPath : IWorkingPath
    {
        public required string WorkingFolder { get; set; }
    }
    
    public class AppSettings : WorkingPath
    {
        public bool IsStaging { get; set; }
        public bool IsStagingTrackAndTrace { get; set; }
    }
    

    然后我的 appsettings.json .

    "AppSettings": {
      "IsStaging": true,
      "IsStagingTrackAndTrace": true,
      "WorkingFolder": "Xxxxx"
    },
    

    然后,我将这些设置提供给依赖项注入。

    AppSettings? appSettings = builder.Configuration.GetSection("AppSettings").Get<AppSettings>();
    builder.Services.AddSingleton(appSettings);
    

    这很好,但现在我有一些类正在请求 IWorkingPath 依赖项注入。

    有什么办法做同样的吗 appSettings 实例可用于依赖项注入,作为 AppSettings I工作路径 ?

    1 回复  |  直到 1 年前
        1
  •  0
  •   Dai    1 年前

    有什么办法做同样的吗 appSettings 实例可用于依赖项注入,作为 AppSettings IWorkingPath ?

    是的,只需注册如下:

    AppSettings appSettings = builder.Configuration.GetSection("AppSettings").Get<AppSettings>() ?? throw new InvalidOperationException( "Failed to get AppSettings instance" );
    
    builder.Services.AddSingleton<IWorkingPath>( appSettings );
    builder.Services.AddSingleton<WorkingPath >( appSettings );
    builder.Services.AddSingleton<AppSettings >( appSettings );
    

    …但更好的解决方案是 class WorkingPath 实现 internal (或者把它移到一个名字吓人的地方 namespace )以避免消费者要求 class ctor参数而不是 I工作路径 界面