【问题标题】:Dynamically Updating Dependency Injection Service动态更新依赖注入服务
【发布时间】:2016-04-28 20:44:04
【问题描述】:

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

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

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

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

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

如何在不将服务从单例更改为瞬态的情况下做到这一点?

感谢您提供的任何帮助!

【问题讨论】:

  • GetSettings是如何实现的?
  • 我不明白为什么ISetting 也是单身,因为ISettingsService 已经准备好了。为什么不将它用作瞬态或作用域,让单身的SettingsService 解决它?
  • @YacoubMassad - GetSiteSettings 返回一个 ISiteSettings 对象,它是从对数据库的查询中创建的。
  • @Fabien - 除了将 ISettings 更改为 AddTransient 之外,我还需要做些什么吗?我试过了,没有发现明显的变化。
  • 一种方法(这可能不是最干净的方法)是让GetSettings 返回ISettings 的智能实现。这种实现从一组初始设置(来自数据库的设置)开始,但随后可以返回一组新设置。此实现将为您提供设置新设置的方法。

标签: c# dependency-injection asp.net-core asp.net-core-mvc


【解决方案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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-07
    • 2020-09-09
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多