khrave
khrave

Reputation: 173

Dynamically Updating Dependency Injection Service

Background: Asp.Net Core website using Dependency Injection to relay needed services to various parts of the website

I have a service that is being added to the IServiceCollection in the ConfigureServices method in my Startup class as a singleton in the following manner:

//Settings
services.AddSingleton<ISettingsService, SettingsService>();
services.AddSingleton<ISettingsIO, SettingsIO>();
services.AddSingleton<ISettings>(f =>
{
    return f.GetService<ISettingsService>().GetSettings();
});

This works great and all the pages/controllers I need to have access to Example can do so without issue.

However, I now have the capability to change the data that is being pulled in the method GetSettings(). This means that I need to update the service that is added to the ServiceCollection.

How can I do this without changing the service from a singleton to transient?

Thanks for any help provided!

Upvotes: 2

Views: 5483

Answers (1)

Yacoub Massad
Yacoub Massad

Reputation: 27871

As I said in the comment, this is not very clean. I think that a better solution would require more information about your system.

Create a mutable settings wrapper class:

public class MyMutableSettings : ISettings
{
    public ISettings Settings {get;set;}

    //Implement the ISettings interface by delegating to Settings, e.g.:
    public int GetNumberOfCats()
    {
        return Settings.GetNumberOfCats();
    }
}

And then you can use it like this:

MyMutableSettings mySettings = new MyMutableSettings();

services.AddSingleton<ISettings>(f =>
{
    mySettings.Settings = f.GetService<ISettingsService>().GetSettings();

    return mySettings;
});

Then, when you want to change the settings:

mySettings.Settings = GetMyNewSettings();

Upvotes: 1

Related Questions