有什么方法可以在启动时从 .net 核心数据库中可用的 JSON 设置初始化 c# 的设置模型?

Is there any way to initialize settings model of c# on startup from the JSON settings available in the database in .net core?

我创建了一个 Web 应用程序,我在其中使用 .net core 3.0 作为服务器端技术,并使用 Postgres 作为后端。我在数据库中有一个名为 settings 的 table,我使用 Postgres 中可用的 JSON 数据类型将设置存储为 JSON。

现在我想根据数据库中可用的 JSON 数据在应用程序中初始化我的设置模型。我想在应用程序启动时初始化模型,并在整个应用程序的任何需要的地方使用它,以避免数据库往返以按需从数据库中获取设置。

有什么办法可以实现吗?

数据库中的Json数据如下:

{
    "CurrencyCode": "USD",
    "CurrencySymbol": "$"
}

这是我在应用程序中的 C# 模型

public class SettingsModel
{
    public string CurrencySymbol { get; set; }

    public string CurrencyCode { get; set; }
}

我正在考虑通过以下方式实现此目的,但仍然不知道使用什么以及如何使用它。

正在使用单例服务初始化模型

services.AddSingleton<SettingsModel, GetJsonSettingsFromDatabase()>();

GetJsonSettingsFromDatabase() 将 return SettingsModel 在将设置从 DB 反序列化到 SettingsModel 之后。

我还想要一些包含更新 SettingsModel 的逻辑的函数,这样当数据库 table 中的设置发生变化时我可以调用相同的函数。

使用单例服务初始化模型应该使用工厂委托

例如

services.AddSingleton<SettingsModel>(sp => return GetJsonSettingsFromDatabase());

假设

GetJsonSettingsFromDatabase() will return the SettingsModel after deserializing the settings from DB to SettingsModel.

实例也可以这样做

SettingsModel settings = GetJsonSettingsFromDatabase();
services.AddSingleton(settings);

至于

I also wanted some function that will contain the logic for updating the SettingsModel so that I can invoke the same when there are changes in the database table for settings.

那就不要注册成单例了。考虑缓存设置实例以避免往返并仅在需要时加载新实例。