自此多章都以教课大旨类库的,所以得考虑规划四个通用的模块来管理那一个字典数据

       
框架中的“通用字典数据配置管理”重要化解的题材是,全数的行业软件给客户实施第3步一般都以基础数据的保障,一个类别的字典是必备的,涉及业务范围越广字典就越多,如若每一个字典数据都做一个界面来展开保证数据来说,那开发工作量依然比较大的,所以得考虑设计3个通用的模块来保管这个字典数据;

     
从本章开首对框架的讲叙先导进入中央类库的执教,前面都以对框架外在功用讲解,令人有个总体的定义,知道包罗如何功能与对系统开发有何样帮忙。今后多章都以教师核心类库的,讲解的不二法门基本遵守代码的目录结构,那样阅读代码的时候也足以针对看;还有就是为着更好精通作品中的内容把最近还不够完美的源代码发表,这么些版本Winform部分骨干得以向来运营,而Web部分与WCF部分的控制器代码没有做到,所以暂且还运转不起来,可是那并不影响学习为主类库,再不怕不久在下个本子公布3个一体化版本给我们;

style=”font-size: 14px; font-family: ‘Microsoft YaHei’;”>本文要点:

 

style=”font-family: ‘Microsoft YaHei’; font-size: 14px;”>1)功效清单介绍

style=”font-family: ‘Microsoft YaHei’; font-size: 14px;”>2)成效界面呈现

style=”font-family: ‘Microsoft YaHei’; font-size: 14px;”>3)核心工作流程图与数据库表关系图

style=”font-family: ‘Microsoft YaHei’; font-size: 14px;”>4)关键点的技能完结代码

EnterpriseFrameWork框架源代码V1.0下载http://pan.baidu.com/s/1pJsMLlx

 

style=”font-size: 15px; font-family: ‘Microsoft YaHei’;”> 本文要点:

style=”font-size: 15px; font-family: ‘Microsoft YaHei’;”>1.EntLib配置文件

style=”font-size: 15px; font-family: ‘Microsoft YaHei’;”>2.对EntLib举行包装

style=”font-size: 15px; font-family: ‘Microsoft YaHei’;”>3.EntLib完毕数据库访问

style=”font-size: 15px; font-family: ‘Microsoft YaHei’;”>4.EntLib贯彻错误日志记录

style=”font-size: 15px; font-family: ‘Microsoft YaHei’;”>5.EntLib兑现缓存管理

style=”font-size: 15px; font-family: ‘Microsoft YaHei’;”>6.EntLib实现AOP与目的创制

1)通用字典管理功用清单

模块名称

作用名称

成效表达

系统字典数据

基础数据配置

字典分类目录,新增、修改、删除
字典管理,
1)采取数据库表添加字典
2)依据数据库表字段,生成界面控件元素
3)对数据库表进行增、删、改、查操作

多少权限设置

安排类别剧中人物能够操作的字典

基础数据管理

依据用户登录的角色呈现可以操作的字典
字典维护,增、删、改、查操作

 

 

2)通用字典管理界面显得,包蕴Winform版和Web版

 图片 1

图片 2

 

图片 3

图片 4

图片 5

图片 6

 

着力类库EFWCoreLib目录结构

3)通用字典管理大旨工作流程图与数据库表关系图

 图片 7

图片 8

 

 图片 9

4)通用字典管理关键点技术实现

1.字典保存数据达成

图片 10图片 11

//保存数据
        public Object SaveResultDataTable(int titleId, string IdName, object IdValue, Dictionary<string, object> fieldAndValue)
        {
            if (IdValue.Equals(System.DBNull.Value) == true)//插入数据
            {
                string fields = "";
                string values = "";
                string strsql = "insert into {0} ({1}) values({2})";

                foreach (KeyValuePair<string, object> val in fieldAndValue)
                {
                    fields += (fields == "" ? "" : ",") + val.Key;
                    values += (values == "" ? "" : ",") + ConvertDBValue(val.Value);
                }

                BaseGeneralTitle title = NewObject<BaseGeneralTitle>().getmodel(titleId) as BaseGeneralTitle;
                IdValue = oleDb.InsertRecord(string.Format(strsql, title.TableName, fields, values));
            }
            else//更新数据
            {
                string field_values = "";

                string strsql = "update  {0} set {1} where {2}";

                foreach (KeyValuePair<string, object> val in fieldAndValue)
                {
                    field_values += (field_values == "" ? "" : ",") + val.Key + "=" + ConvertDBValue(val.Value);
                }

                BaseGeneralTitle title = NewObject<BaseGeneralTitle>().getmodel(titleId) as BaseGeneralTitle;
                oleDb.DoCommand(string.Format(strsql, title.TableName, field_values, IdName + "=" + ConvertDBValue(IdValue)));
            }

            return IdValue;
        }

View Code

2.Web版JqueryEasyUI的Gird控件动态列

图片 12图片 13

<div id="resulttool" class="toolbar">
    <a href="#" class="easyui-linkbutton" plain="true" iconCls="icon-search" onclick="btnresult_search();">查询</a>
    <a href="#" class="easyui-linkbutton" plain="true" iconCls="icon-add" onclick="btnresult_addData();">增加</a>
    <a href="#" class="easyui-linkbutton" plain="true" iconCls="icon-edit" onclick="btnresult_editData();">编辑</a>
    <a href="#" class="easyui-linkbutton" plain="true" iconCls="icon-cancel" onclick="btnresult_delData();">删除</a>
</div>
<table id="resultGird"  class="easyui-datagrid" fit="true" border="false" toolbar="#resulttool" iconCls="icon-edit" pagination="true" idField="<%=Session["resulstDataKeyName"]%>">
 <thead>
    <tr>
        <th field="ck" checkbox="true"></th>
        <%=Session["resulstDatacolmodel"]%>
    </tr>
</thead>
</table>

View Code

 

     
EnterpriseFrameWork框架的最底层功效是使用微软公司库(EntLib)来促成的,包涵选择EntLib的The Data Access Application Block完结数据库访问,The Caching Application Block实行缓存管理,The Exception Handling Application Block进行充裕处理,The Logging Application Block举行日志记录,Unity Dependency Injection and Interception注重注入容器举行对象映射;在这个作用之上再拓展了2回封装,让大家再编辑代码进程中更简短的使用,还有即便EntLib未来晋升也不要求修改系统中的代码;

 

 

style=”font-size: 15px; font-family: ‘Microsoft YaHei’;”>微软公司库的一些读书材质:

 

style=”font-size: 15px; font-family: ‘Microsoft YaHei’;”>Enterprise Library 5.0.msi安装包:http://pan.baidu.com/s/1gdnDz7l

style=”font-size: 15px; font-family: ‘Microsoft YaHei’;”>Enterprise Library 5.0认证文档:http://pan.baidu.com/s/1pJjtvCZ

style=”font-size: 15px; font-family: ‘Microsoft YaHei’;”>CHM版表明文书档案:http://pan.baidu.com/s/1c0rhtba

style=”font-size: 15px; font-family: ‘Microsoft YaHei’;”>学习实例代码:http://pan.baidu.com/s/1dDthk3Z

style=”font-size: 15px; font-family: ‘Microsoft YaHei’;”>Enterprise Library 5.0源代码:http://pan.baidu.com/s/1mgKDot6

style=”font-size: 15px; font-family: ‘Microsoft YaHei’;”>黄聪:Enterprise Library 5.0 连串教程: style=”font-size: 15px; font-family: ‘Microsoft YaHei’;”>http://www.cnblogs.com/huangcong/archive/2010/06/08/1753988.html

style=”font-size: 15px; font-family: ‘Microsoft YaHei’;”> 

壹 、EntLib配置文件

我们先看web项目Web.config中对EntLib的配备,Winform项目中的是App.config

 图片 14

其中标记的群青部分钦赐了EntLib的完全配置文件Entlib.config,

图片 15图片 16

<configuration>
  <configSections>
    <section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    <section name="cachingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
  </configSections>

  <dataConfiguration defaultDatabase="SQL2005" />

  <connectionStrings>
    <add name="SQL2005" connectionString="Data Source=.;Initial Catalog=3yxx_Cssd;User ID=sa;pwd=1;"
     providerName="System.Data.SqlClient" />
  </connectionStrings>
  <exceptionHandling>
    <exceptionPolicies>
      <add name="HISPolicy">
        <exceptionTypes>
          <add name="All Exceptions" type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
              postHandlingAction="NotifyRethrow">
            <exceptionHandlers>
              <add name="Logging Exception Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                  logCategory="FileLog" eventId="100" severity="Error" title="Enterprise Library Exception Handling"
                  formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"
                  priority="0" />
            </exceptionHandlers>
          </add>
        </exceptionTypes>
      </add>
    </exceptionPolicies>
  </exceptionHandling>
  <loggingConfiguration name="" tracingEnabled="true" defaultCategory="ConsoleLog">
    <listeners>
      <add listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.CustomTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          type="EFWCoreLib.CoreFrame.EntLib.Log.TraceListeners.ConsoleTraceListener, EFWCoreLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
          traceOutputOptions="None" name="ConsoleTraceListener" />
      <add listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.CustomTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          type="EFWCoreLib.CoreFrame.EntLib.Log.TraceListeners.FileTraceListener, EFWCoreLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
          name="FileTraceListener" />
      <add listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.CustomTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          type="EFWCoreLib.CoreFrame.EntLib.Log.TraceListeners.DatabaseTraceListener, EFWCoreLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
          name="DatabaseTraceListener" />
      <add name="Email Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.EmailTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.EmailTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          toAddress="to@example.com" fromAddress="from@example.com"
          filter="Off" />
      <add name="Event Log Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          source="Enterprise Library Logging" formatter="Text Formatter"
          log="" machineName="." traceOutputOptions="None" filter="Error" />
      <add name="Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          fileName="trace.log" formatter="Text Formatter" />
    </listeners>
    <formatters>
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          template="Timestamp: {timestamp}{newline}&#xA;Message: {message}{newline}&#xA;Category: {category}{newline}&#xA;Priority: {priority}{newline}&#xA;EventId: {eventid}{newline}&#xA;Severity: {severity}{newline}&#xA;Title:{title}{newline}&#xA;Machine: {localMachine}{newline}&#xA;App Domain: {localAppDomain}{newline}&#xA;ProcessId: {localProcessId}{newline}&#xA;Process Name: {localProcessName}{newline}&#xA;Thread Name: {threadName}{newline}&#xA;Win32 ThreadId:{win32ThreadId}{newline}&#xA;Extended Properties: {dictionary({key} - {value}{newline})}"
          name="Text Formatter" />
      <add type="EFWCoreLib.CoreFrame.EntLib.Log.Formatters.ZhyTextFormatter, EFWCoreLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
          name="ZhyTextFormatter" />
    </formatters>
    <categorySources>
      <add switchValue="All" name="ConsoleLog">
        <listeners>
          <add name="ConsoleTraceListener" />
        </listeners>
      </add>
      <add switchValue="All" name="FileLog">
        <listeners>
          <add name="Flat File Trace Listener" />
        </listeners>
      </add>
      <add switchValue="All" name="DatabaseLog">
        <listeners>
          <add name="DatabaseTraceListener" />
        </listeners>
      </add>
      <add switchValue="All" name="EmailLog">
        <listeners>
          <add name="Email Trace Listener" />
        </listeners>
      </add>
    </categorySources>
    <specialSources>
      <allEvents switchValue="All" name="All Events" />
      <notProcessed switchValue="All" name="Unprocessed Category" />
      <errors switchValue="All" name="Logging Errors &amp; Warnings">
        <listeners>
          <add name="Event Log Listener" />
        </listeners>
      </errors>
    </specialSources>
  </loggingConfiguration>
  <cachingConfiguration defaultCacheManager="Cache Manager">
    <cacheManagers>
      <add name="Cache Manager" type="Microsoft.Practices.EnterpriseLibrary.Caching.CacheManager, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          expirationPollFrequencyInSeconds="60" maximumElementsInCacheBeforeScavenging="1000"
          numberToRemoveWhenScavenging="10" backingStoreName="NullBackingStore" />
    </cacheManagers>
    <backingStores>
      <add type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.NullBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          name="NullBackingStore" />
    </backingStores>
  </cachingConfiguration>
</configuration>

View Code

 

     
 Entlib.config包涵了多少个节点exceptionHandling、dataConfiguration、loggingConfiguration和cachingConfiguration,分别是对相当的布署、数据库的布署、日志的配置和缓存的配置;其实EntLib.Config配置文件的情节能够合而为一在Web.config和App.Config的安顿文件中,就不要求安顿filePath路径,但是分成独立的文件维护起来自然更方便;

     
此处有个难点,正是非凡filePath钦定路线,Web项目必将要钦命相对路径,而Winform项目钦赐相对路径又有啥不可,相对路径太难为了代码换个地方又要修改此路径;有人化解过的请告诉自身一声;

除了这几个之外上面两处安插,还有3个陈设文件EFWUnity.config,涉及到依靠注入的对象急需在此文件中添加配置;

<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration, Version=2.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  </configSections>
  <unity>
    <assembly name="Books"/>
    <namespace name="Books.Dao"/>
    <container>
      <register type="IBookDao" mapTo="SqlBookDao"></register>
    </container>
  </unity>
</configuration>

 

     
在那之中EntLib配置文件除了手工业修改,集团库还提供了可视化学工业具举办配置,基本上在品种中这么些配置都不要求修改;假如是Winform版针对数据库连接字符串要求加密的话,大概须求工具配置一下,EntLib工具提供了加密的效果;

二 、对EntLib举行李包裹装

     
为了使调用EntLib的更便宜,还有便是以往EntLib升级的话不须求修改太多地方,所以对EntiLib进一步封装;

 全数EntLib对象创制都通过ZhyContainer对象

图片 17图片 18

/// <summary>
    /// 封装企业库容器
    /// </summary>
    public class ZhyContainer
    {
        public static IUnityContainer container = null;
        /// <summary>
        /// 获取依赖注入容器
        /// </summary>
        /// <returns></returns>
        public static IUnityContainer CreateUnity()
        {
            container = new UnityContainer();
            return container;
        }

        public static void AddUnity(UnityConfigurationSection section)
        {
            if (container == null) CreateUnity();
            container.LoadConfiguration(section);
        }

        /// <summary>
        /// 获取数据库对象
        /// </summary>
        /// <returns>数据库对象</returns>
        public static Database CreateDataBase()
        {
            return EnterpriseLibraryContainer.Current.GetInstance<Database>();
        }
        /// <summary>
        /// 获取数据库对象
        /// </summary>
        /// <param name="name">数据库实例名(默认name为空,调用默认数据库实例)</param>
        /// <returns>数据库对象</returns>
        public static Database CreateDataBase(string name)
        {
            return EnterpriseLibraryContainer.Current.GetInstance<Database>(name);
        }
        /// <summary>
        /// 获取日志写入对象
        /// </summary>
        /// <returns></returns>
        public static LogWriter CreateLog()
        {
            return EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
        }

        public static LogWriter CreateLog(string name)
        {
            return EnterpriseLibraryContainer.Current.GetInstance<LogWriter>(name);
        }
        /// <summary>
        /// 获取日志跟踪对象
        /// </summary>
        /// <returns></returns>
        public static TraceManager CreateTrace()
        {
            return EnterpriseLibraryContainer.Current.GetInstance<TraceManager>();
        }
        /// <summary>
        /// 获取异常处理对象
        /// </summary>
        /// <returns></returns>
        public static ExceptionManager CreateException()
        {
            return EnterpriseLibraryContainer.Current.GetInstance<ExceptionManager>();
        }

        public static ICacheManager cacheManager = null;
        /// <summary>
        /// 获取缓存对象
        /// </summary>
        /// <returns></returns>
        public static ICacheManager CreateCache()
        {

            cacheManager = CacheFactory.GetCacheManager();
            return cacheManager;
        }

        public static ICacheManager CreateCache(string name)
        {
            cacheManager = EnterpriseLibraryContainer.Current.GetInstance<ICacheManager>(name);
            return cacheManager;
        }
    }

View Code

 

针对EntLib缓存对象ICacheManager的操作封装成CacheHelper对象

图片 19图片 20

 /// <summary>
    /// 缓存操作类
    /// </summary>
    public static class CacheHelper
    {
        private static ICacheManager cache = ZhyContainer.CreateCache();
        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public static void Add(string key, object value)
        {
            cache.Add(key, value);
        }

        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="isRefresh">是否刷新</param>
        public static void Add(string key, object value, bool isRefresh)
        {
            if (isRefresh)
            {
                //自定义刷新方式,如果过期将自动重新加载,过期时间为5分钟
                cache.Add(key, value, CacheItemPriority.Normal, new MyCacheItemRefreshAction(), new AbsoluteTime(TimeSpan.FromMinutes(5)));
            }
            else
            {
                cache.Add(key, value);
            }
        }
        /// <summary>
        /// 缓存是否存在此数据
        /// </summary>
        /// <param name="key">键</param>
        /// <returns></returns>
        public static bool Contains(string key)
        {
            return cache.Contains(key);
        }

        /// <summary>
        /// 获取缓存对象
        /// </summary>
        /// <param name="key">键</param>
        /// <returns></returns>
        public static object GetCache(string key)
        {
            return cache.GetData(key);
        }

        /// <summary>
        /// 移除缓存对象
        /// </summary>
        /// <param name="key">键</param>
        public static void RemoveCache(string key)
        {
            cache.Remove(key);
        }
    }

View Code

 

针对EntLib日志跟踪记录操作封装成LogHelper对象

图片 21图片 22

/// <summary>
    /// 日志操作类
    /// </summary>
    public static class LogHelper
    {
        private static LogWriter logw = ZhyContainer.CreateLog();
        private static TraceManager traceMgr = ZhyContainer.CreateTrace();
        private static LogEntry loge = new LogEntry();
        /// <summary>
        /// 开始跟踪
        /// </summary>
        /// <returns></returns>
        public static Tracer StartTrace()
        {
            return traceMgr.StartTrace(Category.FileLog);
        }
        /// <summary>
        /// 结束跟踪
        /// </summary>
        /// <param name="trace"></param>
        public static void EndTrace(Tracer trace)
        {
            trace.Dispose();
        }

    }

View Code

 

叁 、EntLib达成数据库访问

行使EntLib对数据库的走访万分简单,先成立三个数据库对象Database

public SqlServerDb(string key)
            : base()
        {

            database = ZhyContainer.CreateDataBase(key);
            _connString = database.ConnectionString;
          }

 

使用Database对象进行SQL语句

  public override int DoCommand(string commandtext)
        {
            if (isInTransaction)
            {
                command = database.GetSqlStringCommand(commandtext);
                command.Connection = connection;
                command.Transaction = transaction;
                command.CommandType = CommandType.Text;
                return database.ExecuteNonQuery(command,transaction);
            }
            else
            {
                return database.ExecuteNonQuery(CommandType.Text, commandtext);
            }
          }

 

     
 那阵子让自家动用EntLib的最关键的来头正是它辅助多数据库访问与数据库连接池。数据库连接是简单财富,它们的服服帖帖保管对可扩充的应用程序来说是格外首要的,守旧的DbHelper都是在应用完后必须关闭和自由财富,而采用集团库中的Database对象操作数据库大家不用本身处理,公司库会自动处理。

EntLib数据访问程序块资料参考:http://www.cnblogs.com/shanyou/archive/2008/05/25/1206898.html

 

④ 、EntLib实现错误日志记录

     
程序中著录日志是很关键的,好的日志记录情势能够提供大家足足多定位问题的基于;假设只是独自需求日志成效个人推举Log4net,使用起来更简约;

先看记录的日志文件内容,日志文件是坐落根目录的trace.log文件中

 图片 23

 

伍 、EntLib完毕缓存管理

     
 在创设公司级分布式应用程序时,架构师和开发人士面临着无数难点。缓存可以支持你克服个中的片段难点,包含:

*性能:通过存款和储蓄与数码使用者尽量接近的连带数据,缓存能够增加应用程序的品质。那样能够制止双重进行多少创造、处理和传导。*

*可伸缩性:在缓存中储存新闻有助于节省财富,并且能够随着应用程序供给的扩展来压实可伸缩性*

*可用性:通过将数据存款和储蓄在本地缓存中,应用程序基本上能用系统的故障,例如互联网等待时间、Web 服务难题以及硬件故障*

     

     
其实作者动用缓存想法相当的粗略,正是全局访问的数量本人都存入缓存中,不用缓存也能一挥而就那您得定义很多静态公共变量,但那些代码实现起来相比麻烦;

1)框架中OMuranoM模块对实体的自定义标签配置利用了缓存

 cache.Add(“entityAttributeList”, entityAttributeList);

2)控制器中对配置的内容也选拔了缓存

cache.Add(“cmdWebController”, cmdControllerList);

 

陆 、EntLib完结AOP与对象创造

框架中基于EntLib的AOP完结比较简单,先看哪样运用AOP:

 图片 24

地点是数据库事务处理利用AOP拦截方法落成;

1)定义自定义标签AOPAttribute

图片 25图片 26

/// <summary>
    /// AOP标签
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property |AttributeTargets.Interface)]
    public class AOPAttribute : HandlerAttribute
    {
        private List<Type> _types;
        /// <summary>
        /// 创建AOPAttribute实例
        /// </summary>
        /// <param name="types">AOP操作类类型数组</param>
        public AOPAttribute(params Type[] types)
        {
            _types = types.ToList();
        }
        /// <summary>
        /// 创建AOP管理对象
        /// </summary>
        /// <param name="container">示例容器</param>
        /// <returns></returns>
        public override ICallHandler CreateHandler(Microsoft.Practices.Unity.IUnityContainer container)
        {
            if (_types.Count > 0)
            {
                return new AopCallHandler(_types);
            }

            return null;
        }
    }

View Code

2)AOP操作接口,包涵前处理和后处理

  /// <summary>
    /// IAopOperator AOP操作符接口,包括前处理和后处理
    /// </summary>
    public interface IAopOperator
    {
        /// <summary>
        /// 前处理
        /// </summary>
        /// <param name="input"></param>
        void PreProcess(IMethodInvocation input);
        /// <summary>
        /// 后处理
        /// </summary>
        /// <param name="input"></param>
        /// <param name="result"></param>
        void PostProcess(IMethodInvocation input, IMethodReturn result);
    }

3)AOP调用管理类

图片 27图片 28

/// <summary>
    /// AOP调用管理类
    /// </summary>
    public class AopCallHandler : ICallHandler
    {
        private List<IAopOperator> _list;  //AOP操作对象列表
        /// <summary>
        /// 创建AopCallHandler实例
        /// </summary>
        /// <param name="list">AOP操作类类型列表</param>
        public AopCallHandler(List<Type> list)
        {
            _list = new List<IAopOperator>();
            for (int i = 0; i < list.Count; i++)
            {
                _list.Add((IAopOperator)Activator.CreateInstance(list[i]));
            }
        }
        #region ICallHandler 成员
        /// <summary>
        /// 调用执行
        /// </summary>
        /// <param name="input"></param>
        /// <param name="getNext"></param>
        /// <returns></returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            IMethodReturn result;
            for (int i = 0; i < _list.Count; i++)
            {
                _list[i].PreProcess(input);
            }
            //log
            result = getNext()(input, getNext);
            //if (result.Exception == null)
            //{
            //    Logger.Write("Action Done.");
            for (int i = _list.Count - 1; i >= 0; i--)
            {
                _list[i].PostProcess(input, result);
            }
            //}
            //log

            return result;
        }
        /// <summary>
        /// 执行顺序
        /// </summary>
        public int Order
        {
            get;
            set;
        }

        #endregion
    }

View Code

4)最终创立叁个AOP事务处理类,继承接口IAopOperator作用在前处理和后甩卖多个法子中贯彻

图片 29图片 30

public class AopTransaction : IAopOperator
    {
        public AopTransaction()
        {
        }

        #region IAopOperator 成员

        public void PreProcess(Microsoft.Practices.Unity.InterceptionExtension.IMethodInvocation input)
        {
            List<AbstractDatabase> _RdbList = ((IbindDb)input.Target).GetMoreDb();
            AbstractDatabase Rdb = ((IbindDb)input.Target).GetDb();
            if (_RdbList == null)
            {
                Rdb.BeginTransaction();
            }
            else
            {
                foreach (AbstractDatabase db in _RdbList)
                {
                    db.BeginTransaction();
                }
            }
        }

        public void PostProcess(Microsoft.Practices.Unity.InterceptionExtension.IMethodInvocation input, Microsoft.Practices.Unity.InterceptionExtension.IMethodReturn result)
        {
            List<AbstractDatabase> _RdbList = ((IbindDb)input.Target).GetMoreDb();
            AbstractDatabase Rdb = ((IbindDb)input.Target).GetDb();
            if (_RdbList == null)
            {
                if (result.Exception == null)
                {
                    Rdb.CommitTransaction();
                }
                else
                {
                    Rdb.RollbackTransaction();
                }
            }
            else
            {
                List<AbstractDatabase> RdbList = new List<AbstractDatabase>();
                foreach (AbstractDatabase db in _RdbList)
                {
                    RdbList.Add(db);
                }
                RdbList.Reverse();//反序

                if (result.Exception == null)
                {
                    foreach (AbstractDatabase db in RdbList)
                    {
                        db.CommitTransaction();
                    }
                }
                else
                {
                    foreach (AbstractDatabase db in RdbList)
                    {
                        db.RollbackTransaction();
                    }
                }
            }
        }

        #endregion
    }

View Code

 

EntLib实现AOP学习参考:http://www.cnblogs.com/artech/archive/2008/11/27/1342309.html

 

行使EntLib的Unity制造逻辑层对象,比如Dao对象、ObjectModel对象,那一个目的都不可能用new关键字来创制;

Book book = NewObject<Book>();

public T NewObject<T>()
        {
            T t = FactoryModel.GetObject<T>(_oleDb,_container, null);
            return t;
        }

public static T GetObject<T>(AbstractDatabase Db,IUnityContainer _container, string unityname)
        {
            if (Db == null)
            {
                EFWCoreLib.CoreFrame.DbProvider.AbstractDatabase Rdb = EFWCoreLib.CoreFrame.DbProvider.FactoryDatabase.GetDatabase();
                //SysLoginRight currLoginUser = (SysLoginRight)EFWCoreLib.CoreFrame.Init.AppGlobal.cache.GetData("RoleUser");
                //Rdb.WorkId = currLoginUser.WorkId;
                Db = Rdb;
                _container = EFWCoreLib.CoreFrame.Init.AppGlobal.container;
            }

            //读unity配置文件把类注入到接口得到对象实例
            IUnityContainer container = _container;

            T t = default(T);
            if (unityname == null)
                t = container.Resolve<T>();
            else
                t = container.Resolve<T>(unityname);

            IbindDb ibind = (IbindDb)t;
            ibind.BindDb(Db,container);

            //给对象加上代理
            t = (T)PolicyInjection.Wrap(t.GetType(), t);
            return t;
        }

 

 借使觉得此框架对你富有援救,请关怀本人的博客,后续文章会持续更新!