Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make an object available from dependency injection via more than one type

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 appSettings instance available for dependency injection as either AppSettings or IWorkingPath?

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading