美文网首页.NET商城ABP
通用配置模块的设计

通用配置模块的设计

作者: 圣杰 | 来源:发表于2018-09-02 17:32 被阅读53次

    引言

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

    约定优于配置(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文件,有兴趣的不妨一探究竟。

    相关文章

      网友评论

      • 失足的boy:你好请问为什么我用类库实现ITypeList无法实现,报非泛型类型不能与参数类型一起使用

      本文标题:通用配置模块的设计

      本文链接:https://www.haomeiwen.com/subject/tjqrwftx.html