Abp通用配置模块的设计

引言

约定优于配置,配置趋于灵活

约定优于配置(convention over configuration),也称作按约定编程,是一种软件设计范式,旨在减少软件开发人员需做决定的数量,获得简单的好处,而又不失灵活性。(这个约定,常见于团队开发规范、项目结构、代码规范、数据库军规等等。)

配置趋于灵活,这句话是我总结的。虽然推崇约定优于配置,但一个大型的复杂项目,总有这样那样的配置项,需要提供给用户配置或外置于配置文件中,以供灵活变更。

那如何设计一个通用的配置模块呢?

下面我将尝试用最简单易懂的方式,对Abp源码中通用配置模块的实现方式加以提炼和精简,尽量继承原作者的设计思想,给大家呈现通用配置模块的“最佳实践”。

提炼通用要素

上面提到的是通用配置模块的设计,那我们就需要提炼通用部分。

  1. 配置的定义:都是基于Key/Value的配置项
  2. 配置的设置方式:代码预置或外部配置文件预置
  3. 配置的持久化
  4. 配置值的读取

配置的定义

简单来说,配置的定义主要包含:

  1. 配置的名称
  2. 配置的默认值
  3. 配置的简要描述
  4. 配置的应用范围

SettingDefinition就是对配置定义的抽象:

/// <summary>
/// Defines a setting
/// </summary>
public class SettingDefinition
    {
        /// <summary>
        /// Unique name of the setting.
        /// </summary>
        public string Name { get; private set; }

        /// <summary>
        /// Default value of the setting.
        /// </summary>
        public string DefaultValue { get; set; }

        /// <summary>
        /// Display name of the setting.
        /// This can be used to show setting to the user.
        /// </summary>
        public string DisplayName { get; set; }

        /// <summary>
        /// A brief description for this setting.
        /// </summary>
        public string Description { get; set; }

        /// <summary>
        /// Scopes of this setting.
        /// Default value: <see cref="SettingScopes.Application"/>.
        /// </summary>
        public SettingScopes Scopes { get; set; }


        public SettingDefinition(string name, string defaultValue, string displayName, string description, SettingScopes scopes)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            Name = name;
            DefaultValue = defaultValue;
            DisplayName = displayName;
            Description = description;
            Scopes = scopes;
        }

        public SettingDefinition(string name, string defaultValue)
            : this(name, defaultValue, null, null, SettingScopes.Application)
        {

        }
    }

SettingScopes枚举:

public enum SettingScopes
{
    /// <summary>
    /// Represents a setting that can be configured/changed for the application level.
    /// </summary>
    Application = 1,

    /// <summary>
    /// Represents a setting that can be configured/changed for each Tenant.
    /// This is reserved
    /// </summary>
    Tenant = 2,

    /// <summary>
    /// Represents a setting that can be configured/changed for each User.
    /// </summary>
    User = 4,

    /// <summary>
    /// Represents a setting that can be configured/changed for all levels
    /// </summary>
    All = Application | Tenant | User
}

配置的设置和读取

有了配置的定义,接下来我们就要考虑配置的设置和读取。 我们先来定义ISettingDefinitionManager接口来读取配置的定义:

public interface ISettingDefinitionManager
{
    /// <summary>
    /// Get the <see cref="SettingDefinition"/> object with the unique name.
    /// </summary>
    /// <param name="name">Unique name of the Setting</param>
    /// <returns>The <see cref="SettingDefinition"/>object.</returns>
    SettingDefinition GetSettingDefinition(string name);

    /// <summary>
    /// Get a list of all setting definitions.
    /// </summary>
    /// <returns>All Settings</returns>
    IEnumerable<SettingDefinition> GetAllSettingDefinitions();
}

再来研究配置的设置。配置的设置有以下几种方式:

  1. 通过代码预置
  2. 通过配置文件预置

像这种一种定义多种实现的需求,我们可以通过策略模式来实现。定义SettingProvider抽象类用于获取配置项:

/// <summary>
/// 设置提供者,用来返回具体的配置项列表。
/// </summary>
public abstract class SettingProvider
{
    public abstract IEnumerable<SettingDefinition> GetSettingDefinitions();
}

如果通过代码预置,可以通过以下方式实现:

public class TestSettingProvider : SettingProvider
{
    public override IEnumerable<SettingDefinition> GetSettingDefinitions()
    {
        return new List<SettingDefinition>()
        {
            new SettingDefinition("EmailSettingNames.DefaultFromAddress", "admin@mydomain.com"),
            new SettingDefinition("EmailSettingNames.DefaultFromDisplayName", "mydomain.com mailer"),
            new SettingDefinition("EmailSettingNames.Smtp.Port", "587"),
            new SettingDefinition("EmailSettingNames.Smtp.Host", "smtp.qq.com"),
            new SettingDefinition("EmailSettingNames.Smtp.UserName", "ysjshengjie@qq.com"),
            new SettingDefinition("EmailSettingNames.Smtp.Password", "123456"),
            new SettingDefinition("EmailSettingNames.Smtp.Domain", ""),
            new SettingDefinition("EmailSettingNames.Smtp.EnableSsl", "true"),
            new SettingDefinition("EmailSettingNames.Smtp.UseDefaultCredentials", "false")

        };
    }
}

如果通过配置文件读取,在.NET Core中可以注入IConfiguration 来获取。

有了统一的配置设置接口,我们肯定需要一个容器来容纳所有的配置项。

/// <summary>
/// 用于提供入口去注入设置提供者类型
/// </summary>
public interface ISettingConfiguration
{
    ITypeList<SettingProvider> Providers { get; }
}
public class SettingConfiguration : ISettingConfiguration
{
    public ITypeList<SettingProvider> Providers { get; private set; }

    public SettingConfiguration()
    {
        Providers = new TypeList<SettingProvider>();
    }
}

有了这个接口,我们通过实例化ISettingConfiguration即可动态添加设置提供者类型。

var settingConfiguration = new SettingConfiguration();
settingConfiguration.Providers.Add<TestSettingProvider>();

有了这个统一的ISettingConfiguration,我们再读取配置就容易多了。我们在实现ISettingDefinitionManager时注入ISettingConfiguration,即可获得系统预置的设置提供者类型。

public class SettingDefinitonManager : ISettingDefinitionManager
{
    private readonly ISettingConfiguration _settingConfiguration;
    private readonly IDictionary<string, SettingDefinition> _settings;

    public SettingDefinitonManager(ISettingConfiguration settingConfiguration)
    {
        _settingConfiguration = settingConfiguration;
        _settings = new Dictionary<string, SettingDefinition>();
    }

    /// <summary>
    /// 初始化(加载系统定义的所有设置项)
    /// </summary>
    public void Initialize()
    {
        foreach (var providerType in _settingConfiguration.Providers)
        {
            if (Activator.CreateInstance(providerType) is SettingProvider provider)
                foreach (var setting in provider.GetSettingDefinitions())
                {
                    _settings[setting.Name] = setting;
                }
        }
    }

    /// <summary>
    /// 根据设置项的名称获取设置定义
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    public SettingDefinition GetSettingDefinition(string name)
    {
        if (!_settings.TryGetValue(name, out var settingDefinition))
        {
            throw new Exception("There is no setting defined with name: " + name);
        }

        return settingDefinition;
    }

    /// <summary>
    /// 获取所有的设置定义
    /// </summary>
    /// <returns></returns>
    public IEnumerable<SettingDefinition> GetAllSettingDefinitions()
    {
        return _settings.Values;
    }
}

至此就完成了配置项的定义、设置和读取。如果对设计模式熟悉的话,这就是传说中的Provider Pattern

配置的持久化

因为配置会因SettingScopes的不同,其对应的值也不同。所以配置的持久化,实际上是针对不同SettingScopes下进行配置值的持久化。据此,我们可以抽象出SettingInfo用来保存具体配置的值。

/// <summary>
/// Represents a setting information.
/// </summary>
[Serializable]
public class SettingInfo
{
    /// <summary>
    /// TenantId for this setting.
    /// TenantId is null if this setting is not Tenant level.
    /// </summary>
    public int? TenantId { get; set; }

    /// <summary>
    /// UserId for this setting.
    /// UserId is null if this setting is not user level.
    /// </summary>
    public long? UserId { get; set; }

    /// <summary>
    /// Unique name of the setting.
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// Value of the setting.
    /// </summary>
    public string Value { get; set; }

    /// <summary>
    /// Creates a new <see cref="SettingInfo"/> object.
    /// </summary>
    public SettingInfo()
    {

    }

    /// <summary>
    /// Creates a new <see cref="SettingInfo"/> object.
    /// </summary>
    /// <param name="tenantId">TenantId for this setting. TenantId is null if this setting is not Tenant level.</param>
    /// <param name="userId">UserId for this setting. UserId is null if this setting is not user level.</param>
    /// <param name="name">Unique name of the setting</param>
    /// <param name="value">Value of the setting</param>
    public SettingInfo(int? tenantId, long? userId, string name, string value)
    {
        TenantId = tenantId;
        UserId = userId;
        Name = name;
        Value = value;
    }
}

据此,定义ISettingStore用于SettingInfo的CURD。

/// <summary>
/// 实现该接口以完成设置项的CURD
/// </summary>
public interface ISettingStore
{
    /// <summary>
    /// Gets a setting or null.
    /// </summary>
    /// <param name="tenantId">TenantId or null</param>
    /// <param name="userId">UserId or null</param>
    /// <param name="name">Name of the setting</param>
    /// <returns>Setting object</returns>
    Task<SettingInfo> GetSettingOrNullAsync(int? tenantId, long? userId, string name);

    /// <summary>
    /// Deletes a setting.
    /// </summary>
    /// <param name="setting">Setting to be deleted</param>
    Task DeleteAsync(SettingInfo setting);

    /// <summary>
    /// Adds a setting.
    /// </summary>
    /// <param name="setting">Setting to add</param>
    Task CreateAsync(SettingInfo setting);

    /// <summary>
    /// Update a setting.
    /// </summary>
    /// <param name="setting">Setting to add</param>
    Task UpdateAsync(SettingInfo setting);

    /// <summary>
    /// Gets a list of setting.
    /// </summary>
    /// <param name="tenantId">TenantId or null</param>
    /// <param name="userId">UserId or null</param>
    /// <returns>List of settings</returns>
    Task<List<SettingInfo>> GetAllListAsync(int? tenantId, long? userId);
}

我们可以根据自己项目的实际情况进行实现。比如在内存中存储,或在数据库中进行持久化。决定权在于我们自己。

配置值的读取

因为ISettingStore已经提供了必要的CURD接口,所以配置项值的读取就很简单。我们仅需根据SettingScopes提供相应的读取接口,在实现时注入ISettingStoreISettingDefinintionManager即可实现配置项值的按需读取。

/// <summary>
/// This is the main interface that must be implemented to be able to load/change values of settings.
/// </summary>
public interface ISettingManager
{
    /// <summary>
    /// Gets current value of a setting.
    /// It gets the setting value, overwritten by application, current tenant and current user if exists.
    /// </summary>
    /// <param name="name">Unique name of the setting</param>
    /// <returns>Current value of the setting</returns>
    Task<string> GetSettingValueAsync(string name);

    /// <summary>
    /// Gets current value of a setting for the application level.
    /// </summary>
    /// <param name="name">Unique name of the setting</param>
    /// <returns>Current value of the setting for the application</returns>
    Task<string> GetSettingValueForApplicationAsync(string name);

    /// <summary>
    /// Gets current value of a setting for a tenant level.
    /// It gets the setting value, overwritten by given tenant.
    /// </summary>
    /// <param name="name">Unique name of the setting</param>
    /// <param name="tenantId">Tenant id</param>
    /// <returns>Current value of the setting</returns>
    Task<string> GetSettingValueForTenantAsync(string name, int tenantId);

    /// <summary>
    /// Gets current value of a setting for a user level.
    /// It gets the setting value, overwritten by given tenant and user.
    /// </summary>
    /// <param name="name">Unique name of the setting</param>
    /// <param name="tenantId">Tenant id</param>
    /// <param name="userId">User id</param>
    /// <returns>Current value of the setting for the user</returns>
    Task<string> GetSettingValueForUserAsync(string name, int? tenantId, long userId);
}

当然也可按需添加修改接口。具体的实现就不再列出。而该类的设计就是门面模式了。

模块梳理

以上就是通用配置模块的设计,在实际使用时,我们只需以下步骤即可:

  1. 注入ISettingConfiguration的默认依赖。
  2. 按需实现SettingProvider并添加到ISettingConfiguration实例的Provider属性中。
  3. 调用ISettingDefinitionManager的实例的Initialize方法,将所有的Provider中定义的配置项加载到内存中。
  4. 注入ISettingDefinitionManager的实例,已完成配置项定义的读取。
  5. 按需实现ISettingStore完成配置项值的持久化。
  6. 注入ISettingManager完成对配置项值的读取。

在.NET Core上的Microsoft.Extensions.Configuration也实现了一套通用配置模块,用于访问基于Key/Value的配置,支持读取命令行参数、环境变量、INI文件、JSON和XML文件,有兴趣的不妨一探究竟。

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏LanceToBigData

HttpClient(二)HttpClient使用Ip代理与处理连接超时

前言   其实前面写的那一点点东西都是轻轻点水,其实HttpClient还有很多强大的功能:   (1)实现了所有 HTTP 的方法(GET,POST,PUT,...

43780
来自专栏领域驱动设计DDD实战进阶

微服务实战(七):落地微服务架构到直销系统(实现命令与命令处理器)

我们先来看看CQRS架构,你对下图的架构还有印象吗?每个组件的功能都还清楚吗?如果有疑问,请查考文章《微服务实战(五):落地微服务架构到直销系统(构建高性能大并...

20530
来自专栏程序员的SOD蜜

使用命名管道实现进程间通信

创建命名管道 命名管道常常用于应用程序之间的通迅,由于不需要进行序列化和反序列化操作,效率是非常高的。相比TCP通信方式,效率更高,但比共享内存要低点。 命名管...

27750
来自专栏Porschev[钟慰]的专栏

Asp.Net统一前后端提示信息方案

要解决的问题 减少弹框前后端代码量 增强可维护性 前后端提示资源统一 可以实现简单的多语言提示方案 增强重用性和易用性       ... ...

22450
来自专栏liulun

ASP.NET CORE Linux发布工具(文件对比 只上传差异文件;自动启停WebServer命令;上传完成自动预热WebServer)

20020
来自专栏菩提树下的杨过

[原创]WCF入门级使用教程(转载请注明出处)

开发环境:vs2008英文版(SP1) + IIS + Windows2003 整个解决方案有4个项目 01.WCF ---Class Libary项目,用于...

21870
来自专栏.NET开发者社区

一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](四)

上一篇《一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](三)》,我们完成了:

22590
来自专栏dotnet & java

WCF 入门 (21)

其实不太了解为什么第21集才讲这个Binding,下面都是一些概念性的东西,不过作为一个入门视频,了解一下也无妨吧。

9450
来自专栏魏琼东

分享一个分布式消息总线,基于.NET Socket Tcp的发布-订阅框架,附代码下载

     在很多MIS项目之中都有这样的需求,需要一个及时、高效的的通知机制,即比如当使用者A完成了任务X,就需要立即告知使用者B任务X已经完成,在通常的情况下...

45800
来自专栏挖坑填坑

使用.net core ABP和Angular模板构建博客管理系统(创建后端服务)

11120

扫码关注云+社区

领取腾讯云代金券