首页 文章

动态更新依赖注入服务

提问于
浏览
1

背景:Asp.Net Core网站使用依赖注入将所需服务转发到网站的各个部分

我有一个服务,以下列方式作为 singleton 添加到我的Startup类的ConfigureServices方法中的IServiceCollection:

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

这很好用,我需要访问Example的所有页面/控制器都可以毫无问题地这样做 .

但是,我现在能够更改GetSettings()方法中提取的数据 . 这意味着我需要 update 添加到ServiceCollection的服务 .

我怎样才能将服务从单例改为瞬态?

感谢您提供的任何帮助!

1 回答

  • 1

    正如我在评论中所说,这不是很干净 . 我认为更好的解决方案需要有关您系统的更多信息 .

    创建一个可变设置包装类:

    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();
        }
    }
    

    然后你可以像这样使用它:

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

    然后,当您想要更改设置时:

    mySettings.Settings = GetMyNewSettings();
    

相关问题