.NET面向上下文架构模式

开发 架构 后端
其实在很多应用框架中到处可以看见上下文的概念,包括.NET本身的设计就建立在这种思想上的。实例化的对象默认存在于系统中的默认上下文中,我们可以构建自己的上下文将对象在运行时进行合理的管理。

1. 上下文概述

上下文:其实就是一个逻辑上的业务、功能区域。在这个逻辑区域里可以有效的进行管理,算是一种制度的约束,也可以理解为某种范围类的数据共享。

其实在很多应用框架中到处可以看见上下文的概念,包括.NET本身的设计就建立在这种思想上的。实例化的对象默认存在于系统中的默认上下文中,我们可以构建自己的上下文将对象在运行时进行合理的管理。

在ASP.NET框架中比较经典的就是HttpContext上下文对象。所有的运行时对象都会逻辑归属到HttpContext上下文中来,如:我们可以使用Request、Response等对象访问HTTP处理的生命周期数据。

在Remoting中跨AppDomin访问也是建立在上下文基础上的,请求的消息通过隧道后序列化到达调用发。王清培版权所有,转载请给出署名

在这些强大的应用框架背后总有着让人难以琢磨的设计秘方,诸多的设计原则、设计模式、丰富的实践经验都将是框架稳定运行的基石。Context算是一个比较完美的逻辑范围设计模式。[王清培版权所有,转载请给出署名]

那么就让我们来领略一下上下文的奥秘吧!

2. 上下文的一般应用

上下文的设计思想绝对的美妙,很多地方一旦进行上下文抽象就能解决很多问题。比如在Remoting中我们可以动态的在上下文中加入很多扩展对上下文中的所有对象进行强制管理,比如:调用某一个方法我们需要进行安全检查,我们可以编写一个满足自己当前项目需求的安全认证插件动态的注入到上下文管理器区域中,在这个地方就体现出上下文的设计优势。

在Web编程中,由于它有着与Winfrom编程很大的差异性,需要将同一组对象同时服务于N个客户端进行使用,而在Winfrom中基本上都是属于单线程的,当然可以手动的开启多线程并行操作。对于ASP.NET每当有新的请求处理时,框架会自动开启新的线程去处理当前的调用,然后这个时候就是需要一个相对于之前操作的独立上下文数据环境,而不是在同一个服务器上的所有线程都是共享的。王清培版权所有,转载请给出署名

那么我们就需要将当前的HTTP处理的相关数据纳入到一个逻辑的上下文进行管理和数据共享。

这么多的优势存在,看来我们是有必要尝试一下这中设计模式了。那么就目前系统开发框架而言我们的上下文能用在哪里呢?我想当务之急就是将分层架构中的所有单条线上的对象进行上下文管理。[王清培版权所有,转载请给出署名]

典型的三层架构:

在一般的三层架构开发过程中我们的调用关系基本都是这样的,利用上下文设计模式我们可以将本来鼓励的对象进行合理的管理。上图中User对象线将是属于User上下文的,Order对象线将是属于Order上下文的。大家互不干扰,可以在这个逻辑上下文中共享数据、设置调用安全策略、设计日志记录方式、甚至可以计算每个方法的性能。

BLL的调用代码:

  1. View Code   
  2.  /***  
  3.   * author:深度训练  
  4.   * blog:http://wangqingpei557.blog.51cto.com/  
  5.   * **/ 
  6.  using System;  
  7.  using System.Collections.Generic;  
  8.  using System.Text;  
  9.  using System.Reflection;  
  10.    
  11.  namespace ConsoleApplication1.BLL  
  12.  {  
  13.      [ContextModule.ContextEveningBound(IsEvening = true)]  
  14.      public class BLL_Order : ContextModule.ContextModuleBaseObject<BLL_Order>  
  15.      {  
  16.          DAL.DAL_Order dal_order = new DAL.DAL_Order();  
  17.    
  18.          [ContextModule.ContextExceptionHandler(OperationSort = 1)]  
  19.          public Model.Model_Order InsertOrderSingle(Model.Model_Order ordermodel)  
  20.          {  
  21.              return ContextModule.ContextAction.PostMethod<DAL.DAL_Order, Model.Model_Order>(  
  22.                  dal_order, dal_order.GetMethodInfo("InsertOrderSingle"), ordermodel);  
  23.          }  
  24.          [ContextModule.ContextExceptionHandler(OperationSort = 1)]  
  25.          public void SendOrder(Model.Model_Order ordermodel)  
  26.          {  
  27.              ContextModule.ContextAction.PostMethod<DAL.DAL_Order, object>(  
  28.                 dal_order, dal_order.GetMethodInfo("SendOrder"), ordermodel);  
  29.          }  
  30.      }  
  31.  } 

 

DAL的执行代码:

  1. View Code   
  2.  /***  
  3.   * author:深度训练  
  4.   * blog:http://wangqingpei557.blog.51cto.com/  
  5.   * **/ 
  6.  using System;  
  7.  using System.Collections.Generic;  
  8.  using System.Text;  
  9.    
  10.  namespace ConsoleApplication1.DAL  
  11.  {  
  12.      [ContextModule.ContextEveningBound(IsEvening = true)]  
  13.      public class DAL_Order : ContextModule.ContextModuleBaseObject<DAL_Order>  
  14.      {  
  15.          [ContextModule.ContextLogHandler(OperationSort = 1)]  
  16.          [ContextModule.ContextSecurityHanlder(OperationSort = 2)]  
  17.          public Model.Model_Order InsertOrderSingle(Model.Model_Order ordermodel)  
  18.          {  
  19.              return new Model.Model_Order() { OrderGuid = Guid.NewGuid(), OrderTime = DateTime.Now };  
  20.          }  
  21.          [ContextModule.ContextLogHandler(OperationSort = 1)]  
  22.          public void SendOrder(Model.Model_Order ordermodel)  
  23.          {  
  24.              Console.WriteLine("订单发送成功!");  
  25.          }  
  26.      }  
  27.  } 

上述代码是我模拟一个上下文的执行过程。

3. 上下文共享区域

在每个独立的上下文环境中应该有一片共享的数据存储区域,以备多个上下文对象访问。这种方便性多半存在于项目比较紧张的修改需求的时候或者加新业务的时候扩展方法用的。BLL调用代码:

  1. View Code   
  2.  [ContextModule.ContextExceptionHandler(OperationSort = 1)]  
  3.          public void UpdateOrderSingle()  
  4.          {  
  5.              Model.Model_Order ordermodel = new Model.Model_Order() { OrderGuid = Guid.NewGuid(), OrderTime = DateTime.Now };  
  6.              //放入上下文共享对象池  
  7.              ContextModule.ContextRuntime.CurrentContextRuntime.SetValue("updateorder", ordermodel);  
  8.              ContextModule.ContextAction.PostMethod<DAL.DAL_Order, object>(  
  9.                  dal_order, dal_order.GetMethodInfo("UpdateOrderSingle"), null);  
  10.          } 

DAL执行代码:

  1. [ContextModule.ContextLogHandler(OperationSort = 1)]  
  2.        public void UpdateOrderSingle()  
  3.        {  
  4.            Model.Model_Order ordermodel =  
  5.                ContextModule.ContextRuntime.CurrentContextRuntime.GetValue("updateorder") as Model.Model_Order;  
  6.        } 

#p#

4. 上下文运行时环境

对于上下文运行时环境的构建需要考虑到运行时是共享的上下文对象。对于纳入上下文管理的所有对象都需要共享或者说是受控于上下文运行时。

上下文构建:

  1. View Code   
  2.  /***  
  3.   * author:深度训练  
  4.   * blog:http://wangqingpei557.blog.51cto.com/  
  5.   * **/ 
  6.  using System;  
  7.  using System.Collections.Generic;  
  8.  using System.Text;  
  9.    
  10.  namespace ContextModule  
  11.  {  
  12.      /// <summary>  
  13.      /// 上下文运行时环境。  
  14.      /// 上下文逻辑运行时环境,环境中的功能都是可以通过附加进来的。  
  15.      /// </summary>  
  16.      public class ContextRuntime : IDisposable  
  17.      {  
  18.          #region IDisposable成员  
  19.          void IDisposable.Dispose()  
  20.          {  
  21.              _currentContextRuntime = null;  
  22.          }  
  23.          #endregion  
  24.    
  25.          protected ContextRuntime() { }  
  26.          private DateTime _initTime = DateTime.Now;  
  27.          /// <summary>  
  28.          /// 获取运行时创建上下文的时间  
  29.          /// </summary>  
  30.          public virtual DateTime InitTime { get { return _initTime; } }  
  31.          private Dictionary<object, object> _runTimeResource = new Dictionary<object, object>();  
  32.          private ContextFilterHandlerMap _filterMap = new ContextFilterHandlerMap();  
  33.          /// <summary>  
  34.          /// 获取上下文中的方法、类过滤器映射表  
  35.          /// </summary>  
  36.          public ContextFilterHandlerMap FilterMap { get { return _filterMap; } }  
  37.          private Guid _initPrimaryKey = Guid.NewGuid();  
  38.          /// <summary>  
  39.          /// 获取运行时创建上下文的唯一标识  
  40.          /// </summary>  
  41.          public virtual Guid InitPrimaryKey { get { return _initPrimaryKey; } }  
  42.          /// <summary>  
  43.          /// 获取上下文共享区域中的数据  
  44.          /// </summary>  
  45.          /// <param name="key">数据Key</param>  
  46.          /// <returns>object数据对象</returns>  
  47.          public virtual object GetValue(object key)  
  48.          {  
  49.              return _runTimeResource[key];  
  50.          }  
  51.          /// <summary>  
  52.          /// 设置上下文共享区域中的数据  
  53.          /// </summary>  
  54.          /// <param name="key">数据Key</param>  
  55.          /// <param name="value">要设置的数据对象</param>  
  56.          public virtual void SetValue(object key, object value)  
  57.          {  
  58.              _runTimeResource[key] = value;  
  59.          }  
  60.    
  61.          [ThreadStatic]  
  62.          private static ContextRuntime _currentContextRuntime;  
  63.          /// <summary>  
  64.          /// 获取当前上下文运行时对象.  
  65.          /// </summary>  
  66.          public static ContextRuntime CurrentContextRuntime { get { return _currentContextRuntime; } }  
  67.          /// <summary>  
  68.          /// 开始运行时上下文  
  69.          /// </summary>  
  70.          /// <returns>ContextRuntime</returns>  
  71.          public static ContextRuntime BeginContextRuntime()  
  72.          {  
  73.              //可以通过配置文件配置上下文运行时环境的参数。这里只是实现简单的模拟。  
  74.              _currentContextRuntime = new ContextRuntime();  
  75.              return _currentContextRuntime;  
  76.          }  
  77.      }  
  78.  } 

对于上下文的入口构建:

  1. using (ContextModule.ContextRuntime.BeginContextRuntime())  
  2.           {  
  3.                
  4.          } 

通过Using的方式我们开始上下文生命周期。

5. 上下文活动对象

上下文对象的绑定需要延后,不能在对象的构建时就创建上下文。

使用后期绑定动态的切入到执行的上下文中。

调用代码,上下文入口:

  1. View Code   
  2.  /***  
  3.   * author:深度训练  
  4.   * blog:http://wangqingpei557.blog.51cto.com/  
  5.   * **/ 
  6.  using System;  
  7.  using System.Collections.Generic;  
  8.  using System.Text;  
  9.  using System.Data;  
  10.  using ConsoleApplication1.BLL;  
  11.  using ConsoleApplication1.Model;  
  12.    
  13.  namespace ConsoleApplication1  
  14.  {  
  15.      public class Program  
  16.      {  
  17.          public static void Main(string[] args)  
  18.          {  
  19.              BLL.BLL_Order order = new BLL.BLL_Order();  
  20.              using (ContextModule.ContextRuntime.BeginContextRuntime())  
  21.              {  
  22.                  Model.Model_Order ordermodel = new Model_Order() { OrderGuid = Guid.NewGuid(), OrderTime = DateTime.Now };  
  23.                  Model.Model_Order resultmodel = ContextModule.ContextAction.PostMethod<BLL.BLL_Order, Model.Model_Order>(order, order.GetMethodInfo("InsertOrderSingle"), ordermodel);  
  24.                  ContextModule.ContextAction.PostMethod<BLL.BLL_Order, object>(order, order.GetMethodInfo("SendOrder"), ordermodel);  
  25.              }  
  26.    
  27.          }  
  28.      }  
  29.  } 

#p#

6. 上下文在分层架构中的运用

有了上下文的核心原型之后我们可以扩展到分层架构中来,对于分层架构的使用其实很有必要,一般的大型业务系统都是混合的使用模式,可能有C/SB/SMobile终端等等。

对于加入Service层之后BLLDAL将位于服务之后,对于来自客户端的调用需要经过一些列的身份验证及权限授予。有了WCF之后面向SOA的架构开发变的相对容易点,对安全、性能、负载等等都很完美,所以大部分的情况下我们很少需要控制BLLDAL的执行运行。

那么没有使用WCF构建分布式的系统时或者是没有分布式的需求就是直接的调用,如WEB的一般开发,从UIBLLDAL。或者是普通的Winfrom的项目、控制台项目属于内网的使用,可能就需要控制到代码的执行。

下面我通过演示一个具体的实例来看看到底效果如何。

我以控制台的程序作为演示项目类型,也使用简单的三层架构。

这个再简单不过了吧,为了演示越简单越好,关键是突出重点。

需求:

DAL对象里面加入一个插入Order实体对象的方法:

  1. View Code   
  2.  /***  
  3.   * author:深度训练  
  4.   * blog:http://wangqingpei557.blog.51cto.com/  
  5.   * **/ 
  6.  using System;  
  7.  using System.Collections.Generic;  
  8.  using System.Text;  
  9.    
  10.  namespace ConsoleApplication1.DAL  
  11.  {  
  12.      [ContextModule.ContextEveningBound(IsEvening = true)]  
  13.      public class DAL_Order : ContextModule.ContextModuleBaseObject<DAL_Order>  
  14.      {  
  15.          [ContextModule.ContextLogHandler(OperationSort = 1)]  
  16.          [ContextModule.ContextSecurityHanlder(OperationSort = 2)]  
  17.          public Model.Model_Order InsertOrderSingle(Model.Model_Order ordermodel)  
  18.          {  
  19.              return new Model.Model_Order() { OrderGuid = Guid.NewGuid(), OrderTime = DateTime.Now };  
  20.          }  
  21.      }  
  22.  } 

在这个类的上面有一个特性ContextEveningBound,该是用来表示当前对象属于后期绑定到上下文的对象。同时该类也继承自一个ContextModuleBaseObject<DAL_Order>泛型类,主要作用是将对象强制的绑定到上下文进行管理。

在方法InsertOrderSingle上面有两个特性,ContextLogHandler是用来记录方法的执行日志,ContextSecurityHanlder是用来在方法执行的过程中强制要求管理员认证。

BLL对象代码:

  1. View Code   
  2.  /***  
  3.   * author:深度训练  
  4.   * blog:http://wangqingpei557.blog.51cto.com/  
  5.   * **/ 
  6.  using System;  
  7.  using System.Collections.Generic;  
  8.  using System.Text;  
  9.  using System.Reflection;  
  10.    
  11.  namespace ConsoleApplication1.BLL  
  12.  {  
  13.      [ContextModule.ContextEveningBound(IsEvening = true)]  
  14.      public class BLL_Order : ContextModule.ContextModuleBaseObject<BLL_Order>  
  15.      {  
  16.          DAL.DAL_Order dal_order = new DAL.DAL_Order();  
  17.    
  18.          [ContextModule.ContextExceptionHandler(OperationSort = 1)]  
  19.          public Model.Model_Order InsertOrderSingle(Model.Model_Order ordermodel)  
  20.          {  
  21.              return ContextModule.ContextAction.PostMethod<DAL.DAL_Order, Model.Model_Order>(  
  22.                  dal_order, dal_order.GetMethodInfo("InsertOrderSingle"), ordermodel);  
  23.          }  
  24.      }  
  25.  } 

在BLL对象里面有一个调用DAL对象方法的实例对象,为了演示简单这里没有加入层的依赖注入设计方案,通过直接调用方式。在BLL方法体中有一个专门用来在上下文中调用方法的接口,这是约束目的是为了能让框架切入到方法的执行之前先执行。具体的设计原理我将在下一篇文章中详细讲解。

在方法的上面有一个ContextExceptionHandler特性,目的是安全的调用DAL对象的方法,在有异常的情况下能通过上下文的方式人性化的提示错误信息。这样我们就不需要频繁的编写捕获异常的代码,看起来也不爽,我们要的是代码的整洁、美丽。

UI调用:

  1. View Code   
  2.  /***  
  3.   * author:深度训练  
  4.   * blog:http://wangqingpei557.blog.51cto.com/  
  5.   * **/ 
  6.  using System;  
  7.  using System.Collections.Generic;  
  8.  using System.Text;  
  9.  using System.Data;  
  10.  using ConsoleApplication1.BLL;  
  11.  using ConsoleApplication1.Model;  
  12.    
  13.  namespace ConsoleApplication1  
  14.  {  
  15.      public class Program  
  16.      {  
  17.          public static void Main(string[] args)  
  18.          {  
  19.              BLL.BLL_Order order = new BLL.BLL_Order();  
  20.              //开启上下文  
  21.              using (ContextModule.ContextRuntime.BeginContextRuntime())  
  22.              {  
  23.                  Model.Model_Order ordermodel = new Model_Order() { OrderGuid = Guid.NewGuid(), OrderTime = DateTime.Now };  
  24.    
  25.                  Model.Model_Order resultmodel =  
  26.                      ContextModule.ContextAction.PostMethod<BLL.BLL_Order, Model.Model_Order>(  
  27.                      order, order.GetMethodInfo("InsertOrderSingle"), ordermodel);  
  28.              }  
  29.    
  30.          }  
  31.      }  
  32.  } 

执行效果:

会先执行日志的记录,然后要求我们输入用户凭证才能继续执行下面的方法。

我输入YES才能继续执行插入的方法。我们可以通过很简单的实现上下文的管理接口,对方法进行控制。

总结:该篇文章只是介绍上下文的作用、原理、优势。下篇文章:“.NET 面向上下文架构模式(实现)”将详细的介绍上下文框架如何开发。

原文链接:http://www.cnblogs.com/wangiqngpei557/archive/2012/07/29/2614220.html

责任编辑:林师授 来源: 王清培的博客
相关推荐

2012-08-10 13:32:08

.NETAOP架构

2017-05-11 14:00:02

Flask请求上下文应用上下文

2022-09-14 13:13:51

JavaScript上下文

2012-12-31 10:01:34

SELinuxSELinux安全

2022-09-15 08:01:14

继承基础设施基础服务

2021-02-15 15:20:08

架构程序员软件

2021-07-26 07:47:36

Cpu上下文进程

2020-07-24 10:00:00

JavaScript执行上下文前端

2023-07-11 10:02:23

2022-05-03 21:01:10

架构项目映射

2017-12-17 17:01:23

限界上下文系统模型

2022-10-28 16:24:33

Context上下文鸿蒙

2009-12-29 09:15:00

2011-06-28 10:55:02

QT QMainWindo 内存泄露

2023-12-10 13:37:23

Python编程上下文管理

2023-06-15 15:45:42

自然语言语言模型

2024-03-14 08:11:45

模型RoPELlama

2020-10-26 15:20:05

架构运维技术

2010-02-25 17:04:54

WCF实例上下文

2022-04-24 15:37:26

LinuxCPU
点赞
收藏

51CTO技术栈公众号