2016-04-28 150 views
1

背景:使用Asp.Net核心网站依赖注入中继需要服务的网站的各个部分动态更新依赖注入服务

我有被添加到IServiceCollection在ConfigureServices方法在我启动服务类如下面的方式

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

这个伟大的工程,所有的网页/控制器我需要访问实例可以这样做没有问题。

但是,我现在有能力更改方法GetSettings()中的数据。这意味着我需要更新添加到ServiceCollection的服务。

我该如何做到这一点没有更改服务从单身到瞬态?

感谢您提供的任何帮助!

+0

GetSettings如何实现? –

+1

我不明白为什么'ISetting'也是单身人士,因为'ISettingsService'已经准备好了。为什么不把它用作transient或scoped,并让单身的'SettingsService'解决它呢? –

+0

@YacoubMassad - GetSiteSettings返回一个ISiteSettings对象,它从查询创建到数据库。 – khrave

回答

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