DotNet 项目中集成 Enterprise Library 数据库访问模块

Enterprise Library 是一个为了由创建复杂企业级应用的开发人员使用的应用程序块的集合。这些应用通常部署广泛且与其他应用和系统相互依赖。另外,他们通常有严格的安全、可靠性和性能需求。

1、安装 Enterprise Library

从官网下载 Enterprise Library 并安装,将类库引用到项目中。

下载地址:https://www.microsoft.com/en-us/download/details.aspx?id=15104

2、定义配置类

WeilogSettings 类:

using System;
using System.Configuration;
using System.ComponentModel;
using System.Security.Permissions;
using System.Configuration.Provider;

// 引用 Weilog 公共程序块公共类库属性空间。
using Weilog.Common.Properties;
// 引用微软企业类库公共应用程序块配置空间。
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

namespace Weilog.Common.Configuration
{
    /// <summary>
    /// 定义配置设置以支持用来配置和管理 Weilog 的基础结构。无法继承此类。
    /// </summary>
    public class WeilogSettings : SerializableConfigurationSection
    {
        #region Fields...

        /// <summary>
        /// 初始化配置节属性集合。
        /// </summary>
        private static ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection();

        /// <summary>
        /// 初始化 Weilog 类库应用程序名称。
        /// </summary>
        private static readonly ConfigurationProperty propApplicationName = new ConfigurationProperty("applicationName", typeof(String), "Weilog", null, StdValidatorsAndConverters.NonEmptyStringValidator, ConfigurationPropertyOptions.IsRequired);

        /// <summary>
        /// 初始化 Weilog 类库应用程序名称。
        /// </summary>
        private static readonly ConfigurationProperty propName = new ConfigurationProperty("name", typeof(String), "Weilog", null, StdValidatorsAndConverters.NonEmptyStringValidator, ConfigurationPropertyOptions.IsRequired);

        /// <summary>
        /// 初始化指定在 <connectionStrings> 元素中定义的连接字符串的名称。
        /// </summary>
        private static readonly ConfigurationProperty propConnectionStringName = new ConfigurationProperty("connectionStringName", typeof(String), "WeilogConnectionString", null, StdValidatorsAndConverters.NonEmptyStringValidator, ConfigurationPropertyOptions.IsRequired);

        /// <summary>
        /// 初始化数据源类型的名称。
        /// </summary>
        private static readonly ConfigurationProperty propType = new ConfigurationProperty("type", typeof(String), "Weilog.Data.SqlServer", null, StdValidatorsAndConverters.NonEmptyStringValidator, ConfigurationPropertyOptions.IsRequired);

        /// <summary>
        /// 初始化允许的无效密码或无效密码提示问题答案尝试的次数。
        /// </summary>
        private static readonly ConfigurationProperty propInterval = new ConfigurationProperty("interval", typeof(Int32), "60000", null, StdValidatorsAndConverters.PositiveIntegerValidator, ConfigurationPropertyOptions.None);

        /// <summary>
        /// Weilog 块配置节名称。
        /// </summary>
        public const string SectionName = "WeilogConfiguration";

        #endregion

        #region Constructors...

        /// <summary>
        /// 初始化 <see cref="WeilogSettings"/> 静态类。
        /// </summary>
        static WeilogSettings()
        {
            // 添加配置节属性对象到集合。
            properties.Add(propApplicationName);
            properties.Add(propConnectionStringName);
            properties.Add(propType);
            properties.Add(propName);
            properties.Add(propInterval);
        }

        /// <summary>
        /// 初始化 <see cref="WeilogSettings"/> 类的新实例。
        /// </summary>
        private WeilogSettings()
        {
        }

        #endregion

        #region Methods...
        #endregion

        #region Properties...

        /// <summary>
        /// 获取或设置要存储和检索其成员资格信息的应用程序的名称。
        /// </summary>
        /// <value>应用程序的名称,将存储和检索该应用程序的成员资格信息。</value>
        [StringValidator(MinLength = 1), ConfigurationProperty("applicationName", DefaultValue = "Weilog", IsRequired = true)]
        public string ApplicationName
        {
            get
            {
                return (string)base[propApplicationName];
            }
            set
            {
                if (String.IsNullOrEmpty(value))
                {
                    throw new ArgumentNullException("ApplicationName");
                }
                if (value.Length > 0x100)
                {
                    throw new ProviderException("Provider_application_name_too_long");
                }

                base[propApplicationName] = value;
            }
        }

        /// <summary>
        /// 获取或设置要存储和检索其成员资格信息的应用程序的名称。
        /// </summary>
        /// <value>应用程序的名称,将存储和检索该应用程序的成员资格信息。</value>
        [StringValidator(MinLength = 1), ConfigurationProperty("name", DefaultValue = "Weilog", IsRequired = true)]
        public string Name
        {
            get
            {
                return (string)base[propName];
            }
            set
            {
                if (String.IsNullOrEmpty(value))
                {
                    throw new ArgumentNullException("Name");
                }
                if (value.Length > 0x100)
                {
                    throw new ProviderException("Provider_name_too_long");
                }

                base[propName] = value;
            }
        }

        /// <summary>
        /// 获取或设置数据库的连接名称。
        /// </summary>
        /// <value>一个字符串,用于指定 connectionStrings 配置节内的数据库连接字符串的名称。</value>
        [StringValidator(MinLength = 1), ConfigurationProperty("connectionStringName", DefaultValue = "WeilogConnectionString", IsRequired = true)]
        public string ConnectionStringName
        {
            get
            {
                return (string)base[propConnectionStringName];
            }
            set
            {
                base[propConnectionStringName] = value;
            }
        }

        /// <summary>
        /// 获取要连接的数据源类型的名称。
        /// </summary>
        /// <value>要连接的数据源类型的名称。</value>
        [StringValidator(MinLength = 1), ConfigurationProperty("type", DefaultValue = "Weilog.Data.SqlServer", IsRequired = true)]
        public string Type
        {
            get
            {
                return (string)base[propType];
            }
            set
            {
                base[propType] = value;
            }
        }

        /// <summary>
        /// 获取锁定成员资格用户前允许的无效密码或无效密码提示问题答案尝试次数。
        /// </summary>
        /// <value>锁定成员资格用户之前允许的无效密码或无效密码提示问题答案尝试次数。</value>
        [ConfigurationProperty("interval", DefaultValue = "60000"), TypeConverter(typeof(Int32))]
        public int Interval
        {
            get
            {
                return (int)base[propInterval];
            }
            set
            {
                base[propInterval] = value;
            }
        }

        /// <summary>
        /// 获取属性的集合。
        /// </summary>
        /// <value><see cref="ConfigurationPropertyCollection"/> 元素的属性集合。</value>
        /// <remarks>Properties 属性 (Property),也被称为属性包,包含应用于该元素的所有属性 (Property) 或属性 (Attribute)。</remarks>
        protected override ConfigurationPropertyCollection Properties
        {
            get
            {
                return properties;
            }
        }

        #endregion
    }
}

WeilogConfigurationManager 类:

using System;
using System.IO;
using System.Configuration;
using System.Collections.Specialized;

// 引用 Weilog 公共程序块公共类库属性空间。
using Weilog.Common.Properties;
// 引用微软企业类库公共应用程序块配置空间。
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

namespace Weilog.Common.Configuration
{
    /// <summary>
    /// 提供对客户端应用程序配置文件的访问。无法继承此类。
    /// </summary>
    public static class WeilogConfigurationManager
    {
        #region Fields...
        #endregion

        #region Constructors...

        /// <summary>
        /// 初始化 <see cref="WeilogConfigurationManager"/> 静态类。
        /// </summary>
        static WeilogConfigurationManager()
        {
        }

        #endregion

        #region Methods...

        /// <summary>
        /// 检索当前应用程序默认配置的指定配置节。
        /// </summary>
        /// <param name="sectionName">配置节的路径和名称。</param>
        /// <returns>指定的 <see cref="ConfigurationSection"/> 对象,或者,如果该节不存在,则为 空引用(在 Visual Basic 中为 Nothing)。</returns>
        private static ConfigurationSection GetSection(string sectionName)
        {
            // 声明配置节点类引用。
            ConfigurationSection _section = null;

            // 声明配置源引用。
            SystemConfigurationSource _systemConfSource = null;

            try
            {
                // 初始化配置源对象。
                _systemConfSource = (SystemConfigurationSource)ConfigurationSourceFactory.Create();
                // 初始化配置信息。
                _section = _systemConfSource.GetSection(sectionName);
            }
            catch
            {
                throw;
            }
            finally
            {
                // 清理对象。
                _systemConfSource = null;
            }

            return _section;
        }

        #endregion

        #region Properties...

        /// <summary>
        /// 获取 Weilog 应用程序块 <see cref="WeilogSettings"/> 配置信息。
        /// </summary>
        /// <value>一个 <see cref="WeilogSettings"/> 对象。</value>
        public static WeilogSettings WeilogConfiguration
        {
            get
            {
                // 初始化 Weilog 配置节信息。
                WeilogSettings weilogSetting = (WeilogSettings)GetSection(WeilogSettings.SectionName);

                return weilogSetting;
            }
        }

        #endregion
    }
}

StdValidatorsAndConverters 类:

using System;
using System.ComponentModel;
using System.Configuration;

namespace Weilog.Common.Configuration
{
    /// <summary>
    /// 提供一组对成员资格配置节的验证和转换标准方法。
    /// </summary>
    internal static class StdValidatorsAndConverters
    {
        #region Fields...

        /// <summary>
        /// 声明无穷 <see cref="TimeSpan"/> 值的类型转换器的引用。
        /// </summary>
        private static TypeConverter _infiniteTimeSpanConverter = null;

        /// <summary>
        /// 声明非空字符串配置验证器的引用。
        /// </summary>
        private static ConfigurationValidatorBase _nonEmptyStringValidator = null;

        /// <summary>
        /// 声明非零负整数验证器的引用。
        /// </summary>
        private static ConfigurationValidatorBase _nonZeroPositiveIntegerValidator = null;

        /// <summary>
        /// 声明负整数验证器的引用。
        /// </summary>
        private static ConfigurationValidatorBase _positiveIntegerValidator = null;

        /// <summary>
        /// 声明负的 <see cref="TimeSpan"/> 值验证器的引用。
        /// </summary>
        private static ConfigurationValidatorBase _positiveTimeSpanValidator = null;

        /// <summary>
        /// 声明 <see cref="TimeSpan"/> 值的分钟数转换器的引用。
        /// </summary>
        private static TypeConverter _timeSpanMinutesConverter = null;

        /// <summary>
        /// 声明 <see cref="TimeSpan"/> 值的无穷分钟数的转换器的引用。
        /// </summary>
        private static TypeConverter _timeSpanMinutesOrInfiniteConverter = null;

        /// <summary>
        /// 声明 <see cref="TimeSpan"/> 值的秒钟数转换器的引用。
        /// </summary>
        private static TypeConverter _timeSpanSecondsConverter = null;

        /// <summary>
        /// 声明 <see cref="TimeSpan"/> 值的无穷秒钟数转换器的引用。
        /// </summary>
        private static TypeConverter _timeSpanSecondsOrInfiniteConverter = null;

        /// <summary>
        /// 声明字符串白空格转换器的引用。
        /// </summary>
        private static TypeConverter _whiteSpaceTrimStringConverter = null;

        #endregion

        #region Constructors...

        /// <summary>
        /// 初始化 <see cref="StdValidatorsAndConverters"/> 静态类。
        /// </summary>
        static StdValidatorsAndConverters()
        {
        }

        #endregion

        #region Methods...
        #endregion

        #region Properties...

        /// <summary>
        /// 获取无穷大的 <see cref="TimeSpan"/> 值转换器实例。
        /// </summary>
        /// <value>一个无穷大的 <see cref="TimeSpan"/> 值转换器实例。</value>
        internal static TypeConverter InfiniteTimeSpanConverter
        {
            get
            {
                if (_infiniteTimeSpanConverter == null)
                {
                    _infiniteTimeSpanConverter = new InfiniteTimeSpanConverter();
                }
                return _infiniteTimeSpanConverter;
            }
        }

        /// <summary>
        /// 获取非空字符串验证器实例。
        /// </summary>
        /// <value>一个非空字符串验证器实例。</value>
        internal static ConfigurationValidatorBase NonEmptyStringValidator
        {
            get
            {
                if (_nonEmptyStringValidator == null)
                {
                    _nonEmptyStringValidator = new StringValidator(1);
                }
                return _nonEmptyStringValidator;
            }
        }

        /// <summary>
        /// 获取非零负整数验证器实例。
        /// </summary>
        /// <value>一个非零负整数验证器实例。</value>
        internal static ConfigurationValidatorBase NonZeroPositiveIntegerValidator
        {
            get
            {
                if (_nonZeroPositiveIntegerValidator == null)
                {
                    _nonZeroPositiveIntegerValidator = new IntegerValidator(1, 0x7fffffff);
                }
                return _nonZeroPositiveIntegerValidator;
            }
        }

        /// <summary>
        /// 获取负整数验证器实例。
        /// </summary>
        /// <value>一个负整数验证器实例。</value>
        internal static ConfigurationValidatorBase PositiveIntegerValidator
        {
            get
            {
                if (_positiveIntegerValidator == null)
                {
                    _positiveIntegerValidator = new IntegerValidator(0, 0x7fffffff);
                }
                return _positiveIntegerValidator;
            }
        }

        /// <summary>
        /// 获取负的 <see cref="TimeSpan"/> 值的验证器实例。
        /// </summary>
        /// <value>一个负的 <see cref="TimeSpan"/> 值的验证器实例。</value>
        internal static ConfigurationValidatorBase PositiveTimeSpanValidator
        {
            get
            {
                if (_positiveTimeSpanValidator == null)
                {
                    _positiveTimeSpanValidator = new PositiveTimeSpanValidator();
                }
                return _positiveTimeSpanValidator;
            }
        }

        /// <summary>
        /// 获取 <see cref="TimeSpan"/> 值分钟数转换器实例。
        /// </summary>
        /// <value>一个 <see cref="TimeSpan"/> 值分钟数转换器实例。</value>
        internal static TypeConverter TimeSpanMinutesConverter
        {
            get
            {
                if (_timeSpanMinutesConverter == null)
                {
                    _timeSpanMinutesConverter = new TimeSpanMinutesConverter();
                }
                return _timeSpanMinutesConverter;
            }
        }

        /// <summary>
        /// 获取 <see cref="TimeSpan"/> 值无穷分钟数转换器实例。
        /// </summary>
        /// <value>一个 <see cref="TimeSpan"/> 值无穷分钟数转换器实例。</value>
        internal static TypeConverter TimeSpanMinutesOrInfiniteConverter
        {
            get
            {
                if (_timeSpanMinutesOrInfiniteConverter == null)
                {
                    _timeSpanMinutesOrInfiniteConverter = new TimeSpanMinutesOrInfiniteConverter();
                }
                return _timeSpanMinutesOrInfiniteConverter;
            }
        }

        /// <summary>
        /// 获取 <see cref="TimeSpan"/> 值秒钟数转换器实例。
        /// </summary>
        /// <value>一个 <see cref="TimeSpan"/> 值秒钟数转换器实例。</value>
        internal static TypeConverter TimeSpanSecondsConverter
        {
            get
            {
                if (_timeSpanSecondsConverter == null)
                {
                    _timeSpanSecondsConverter = new TimeSpanSecondsConverter();
                }
                return _timeSpanSecondsConverter;
            }
        }

        /// <summary>
        /// 获取 <see cref="TimeSpan"/> 值无穷秒钟数转换器实例。
        /// </summary>
        /// <value>一个 <see cref="TimeSpan"/> 值无穷秒钟数转换器实例。</value>
        internal static TypeConverter TimeSpanSecondsOrInfiniteConverter
        {
            get
            {
                if (_timeSpanSecondsOrInfiniteConverter == null)
                {
                    _timeSpanSecondsOrInfiniteConverter = new TimeSpanSecondsOrInfiniteConverter();
                }
                return _timeSpanSecondsOrInfiniteConverter;
            }
        }

        /// <summary>
        /// 获取字符串白空格转换器实例。
        /// </summary>
        /// <value>一个字符串白空格转换器实例。</value>
        internal static TypeConverter WhiteSpaceTrimStringConverter
        {
            get
            {
                if (_whiteSpaceTrimStringConverter == null)
                {
                    _whiteSpaceTrimStringConverter = new WhiteSpaceTrimStringConverter();
                }
                return _whiteSpaceTrimStringConverter;
            }
        }

        #endregion
    }
}

3、定义数据库基类

DbProviderBase 类:

using System;
using System.Collections.Specialized;
using System.Configuration;

//引用 Weilog 公共程序块数据库提供程序属性空间。
using Weilog.DbProvider.Properties;
//引用 Weilog 公共程序块配置空间。
using Weilog.Common.Configuration;

namespace Weilog.DbProvider
{
    /// <summary>
    /// 可扩展的数据库提供程序模型的基类。
    /// </summary>
    public abstract class DbProviderBase
    {
        #region Fields...

        /// <summary>
        /// 声明数据服务名字符串引用。
        /// </summary>
        private string _dbservicestr = null;

        /// <summary>
        /// 声明应用程序名称的字符串引用。
        /// </summary>
        private string _name = null;

        /// <summary>
        /// 声明全局应用程序名称的字符串引用。
        /// </summary>
        private string _applicationName = null;

        #endregion

        #region Constructors...

        /// <summary>
        /// 初始化 <see cref="DbProviderBase"/> 类的新实例。
        /// </summary>
        protected DbProviderBase()
        {
            //引用企业安全类库配置节类引用。 
            WeilogSettings _secSection = null;

            try
            {
                // 初始化企业安全类库配置节信息。
                _secSection = WeilogConfigurationManager.WeilogConfiguration;

                // 判断企业安全类库配置节是否初始化成功。
                if (_secSection == null)
                {
                    // 配置系统未能初始化。
                    throw new Exception("Config_client_config_init_error");
                }

                // 初始化数据服务名称字符串。
                this._dbservicestr = _secSection.ConnectionStringName;
                // 初始化应用程序名。
                this._name = _secSection.Name;
                // 初始化全局应用程序名称。
                this._applicationName = _secSection.ApplicationName;
            }
            catch
            {
                throw;
            }
            finally
            {
                // 清理对象。
                _secSection = null;
            }
        }

        #endregion

        #region Properties...

        /// <summary>
        /// 获取全局应用程序名称。
        /// </summary>
        /// <value>全局应用程序名称。</value>
        public string ApplicationName
        {
            get
            {
                return this._applicationName;
            }
        }

        /// <summary>
        /// 使用自定义成员资格提供程序的应用程序的名称。
        /// </summary>
        /// <value>使用自定义成员资格提供程序的应用程序的名称。</value>
        protected string Name
        {
            get
            {
                return this._name;
            }
        }

        /// <summary>
        /// 获取数据访问服务名称。
        /// </summary>
        /// <value>数据访问服务名称。</value>
        public string DbServiceName
        {
            get
            {
                return this._dbservicestr;
            }
        }

        #endregion
    }
}

4、配置 Web.config

<configSections>
    <section name="weilogConfiguration" type="Weilog.Common.Configuration.WeilogSettings, Weilog.Common"/>
    <weilogConfiguration name="Weilog.Web" applicationName="Weilog" connectionStringName="weilogConnectionString"
                         type="Weilog.Web.Repository" interval="60000"/>
    <connectionStrings>
        <add name="weilogConnectionString"
             connectionString="Data Source=192.168.1.25;Initial Catalog=Weilog;User Id=db_weilog_user;Password=weilog123;"
             providerName="System.Data.SqlClient"/>
    </connectionStrings>
</configSections>

5、使用 Enterprise Library

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;

//引用微软企业类库数据访问应用程序块。
using Microsoft.Practices.EnterpriseLibrary.Data;
//引用公共程序块数据库提供程序类库。
using Weilog.DbProvider;
//引用业务实体类库。
using Weilog.Web.Domain.Entity.CityArea;

namespace Weilog.Web.Repository.CityArea
{
    /// <summary>
    /// 区域信息 SQLServer 数据访问类。无法继承此类。
    /// </summary>
    public sealed class AreaRepository : DbProviderBase
    {
        #region Fields...

        #endregion

        #region Constructors...

        /// <summary>
        /// 初始化 <see cref="AreaRepository"/> 类的新实例。
        /// </summary>
        public AreaRepository()
            : base()
        {
        }

        #endregion

        #region Methods...

        #region 获取指定编码集合的区域信息...

        /// <summary>
        /// 获取指定编码集合的区域信息。
        /// </summary>
        /// <param name="cityId">指定城市唯一编号。</param>
        /// <param name="areaCodes">指定区域编号集合。</param>
        /// <returns>区域信息实体对象。</returns>
        public List<AreaInfo> GetAreaByCodes(int cityId, string areaCodes)
        {
            // 初始化 Database 对象。
            Database db = DatabaseFactory.CreateDatabase(base.DbServiceName);
            // 初始化 DbCommand 对象。
            DbCommand dbcmd = db.GetStoredProcCommand("proc_Web_Area_GetAreaByCodes");

            // 初始化输入参数。
            db.AddInParameter(dbcmd, "@CityId", DbType.Int32, cityId);
            db.AddInParameter(dbcmd, "@AreaCodes", DbType.String, areaCodes.Trim());

            // 声明 IDataReader 数据读取器接口引用。
            IDataReader idr = null;

            // 实例化区域信息实体列表。
            List<AreaInfo> infoList = new List<AreaInfo>();

            try
            {
                // 初始化数据读取器。
                idr = db.ExecuteReader(dbcmd);

                if (idr != null)
                {
                    // 判断是否读取数据。
                    while (idr.Read())
                    {
                        // 实例化区域信息实体对象。
                        AreaInfo areaInfo = new AreaInfo();

                        // 填充字段。
                        areaInfo.Code = idr["Code"] == DBNull.Value ? String.Empty : idr["Code"].ToString().Trim();
                        string text = idr["Text"] == DBNull.Value ? String.Empty : idr["Text"].ToString().Trim();
                        if (string.IsNullOrEmpty(text))
                        {
                            areaInfo.Name = idr["Name"] == DBNull.Value ? String.Empty : idr["Name"].ToString().Trim();
                        }
                        else
                        {
                            areaInfo.Name = text;
                        }
                        // 添加对象到列表。
                        infoList.Add(areaInfo);

                    }
                }

            }
            catch (Exception ee)
            {
                // 写入异常日志表。
                // 抛出异常。
                throw ee;
            }
            finally
            {
                if (idr != null)
                {
                    idr.Close();
                }
            }
            return infoList;
        }

        #endregion

        #endregion

    }
}

以上就是在 DotNet 项目中集成 Enterprise Library 数据库访问模块的全部内容了。

原文地址:https://www.cnblogs.com/weisenz/p/2439036.html