通过多种类型使对象可通过依赖注入

问题描述 投票:0回答: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
IWorkingPath
吗?

c# .net .net-core dependency-injection razor-pages
1个回答
0
投票

有什么方法可以使相同的

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 参数而不是
IWorkingPath
接口。

© www.soinside.com 2019 - 2024. All rights reserved.