I have the following interface and classes.
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; }
}
And then I have the following section in my appsettings.json.
"AppSettings": {
"IsStaging": true,
"IsStagingTrackAndTrace": true,
"WorkingFolder": "Xxxxx"
},
I then make these settings available to dependency injection.
AppSettings? appSettings = builder.Configuration.GetSection("AppSettings").Get<AppSettings>();
builder.Services.AddSingleton(appSettings);
This works fine, but now I have some classes that are requesting IWorkingPath from dependency injection.
Is there any way to make this same appSettings instance available for dependency injection as either AppSettings or IWorkingPath?
>Solution :
Is there any way to make this same
appSettingsinstance available for dependency injection as eitherAppSettingsorIWorkingPath?
Yes, just register it as such:
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 );
…but a better solution would be to make the class WorkingPath implementation an internal (or move it to a scarily-named namespace) to avoid consumers requesting a class ctor parameter instead of the IWorkingPath interface.