EntityFramework中使用Repository装饰器
铺垫
通常在使用 EntityFramework 时,我们会封装出 IRepository 和 IUnitOfWork 接口,前者负责 CRUD 操作,后者负责数据提交 Commit。
public interface IRepository<T>
where T : class
{
IQueryable<T> Query(); void Insert(T entity); void Update(T entity, params Expression<Func<T, object>>[] modifiedPropertyLambdas); void Delete(T entity);
}
public interface IUnitOfWork
{
void Commit();
}
然后,通过使用 Unity IoC 容器来注册泛型接口与实现类型。
Func<IUnityContainer> factory = () =>
{
return new UnityContainer()
.RegisterType(typeof(IRepository<>), typeof(Repository<>), new ContainerControlledLifetimeManager())
.RegisterType<IUnitOfWork, UnitOfWork>(new ContainerControlledLifetimeManager())
.RegisterType<DbContext, MyDBContext>(new ContainerControlledLifetimeManager())
.RegisterType<DbContextAdapter>(new ContainerControlledLifetimeManager())
.RegisterType<IObjectSetFactory, DbContextAdapter>(new ContainerControlledLifetimeManager())
.RegisterType<IObjectContext, DbContextAdapter>(new ContainerControlledLifetimeManager());
};
进而使与数据库相关的操作在 Bisuness Logic 中呈现的非常简单。
例如,通过一系列封装,我们可以达到如下效果:
Customer customer = new Customer()
{
ID = "",
FirstName = "Dennis",
LastName = "Gao",
};
Repository.Customer.Insert(customer);
Repository.Commit();
查询操作也是一句话搞定:
Customer customer = Repository.Customer.Query().SingleOrDefault(c => c.ID == "");
需求
假设有一个新的需求:要求在应用层面记录对每个 Table 的 CRUD 的次数。
这时,有几种办法:
- 应用程序的 Business Logic 中自己记录,比如调用 Update() 操作后记录。
- 使用 AOP 模式,在调用 CRUD 方法时注入计数器。
- 修改 Repository<T> 实现,在每个方法中嵌入计数器。
- 继承 Repository<T> 类,在衍生类中嵌入计数器。
- 使用装饰器模式封装 Repository<T>,在新的 RepositoryDecorator<T> 类中嵌入计数器。
考虑到前三种方法均需要改动已有代码,主要是涉及的修改太多,所有没有尝试采用。
方法 4 则要求修改 Repository<T> 的实现,为 CRUD 方法添加 virtual 关键字以便扩展。
方法 5 不需要修改 Repository<T> 的实现,对已有代码的改动不大。
综上所述,我们选择了方法 5。
Repository 装饰器基类实现
为便于以后的扩展,创建一个装饰器的抽象类。
public abstract class RepositoryDecorator<T> : IRepository<T>
where T : class
{
private readonly IRepository<T> _surrogate; protected RepositoryDecorator(IRepository<T> surrogate)
{
_surrogate = surrogate;
} protected IRepository<T> Surrogate
{
get { return _surrogate; }
} #region IRepository<T> Members public virtual IQueryable<T> Query()
{
return _surrogate.Query();
} public virtual void Insert(T entity)
{
_surrogate.Insert(entity);
} public virtual void Update(T entity, params Expression<Func<T, object>>[] modifiedPropertyLambdas)
{
_surrogate.Update(entity, modifiedPropertyLambdas);
} public virtual void Delete(T entity)
{
_surrogate.Delete(entity);
} #endregion
}
可以看到,RepositoryDecorator<T> 类型仍然实现了 IRepository<T> 接口,对外使用没有任何变化。
实现需求
我们定义一个 CountableRepository<T> 类用于封装 CRUD 计数功能,其继承自 RepositoryDecorator<T> 抽象类。
public class CountableRepository<T> : RepositoryDecorator<T>
where T : class
{
public CountableRepository(IRepository<T> surrogate)
: base(surrogate)
{
} public override IQueryable<T> Query()
{
PerformanceCounter.CountQuery<T>();
return base.Query();
} public override void Insert(T entity)
{
PerformanceCounter.CountInsert<T>();
base.Insert(entity);
} public override void Update(T entity, params Expression<Func<T, object>>[] modifiedPropertyLambdas)
{
PerformanceCounter.CountUpdate<T>();
base.Update(entity, modifiedPropertyLambdas);
} public override void Delete(T entity)
{
PerformanceCounter.CountDelete<T>();
base.Delete(entity);
}
}
我们在 override 方法中,添加了 CRUD 的计数功能。这里的代码简写为:
PerformanceCounter.CountQuery<T>();
对原有代码的修改则是需要注册新的 CountableRepository<T> 类型。
Func<IUnityContainer> factory = () =>
{
return new UnityContainer()
.ReplaceBehaviorExtensionsWithSafeExtension()
.RegisterType(typeof(IRepository<>), typeof(Repository<>), new ContainerControlledLifetimeManager())
.RegisterType(typeof(CountableRepository<>), new ContainerControlledLifetimeManager())
.RegisterType<IUnitOfWork, UnitOfWork>(new ContainerControlledLifetimeManager())
.RegisterType<DbContext, MyDBContext>(new ContainerControlledLifetimeManager())
.RegisterType<DbContextAdapter>(new ContainerControlledLifetimeManager())
.RegisterType<IObjectSetFactory, DbContextAdapter>(new ContainerControlledLifetimeManager())
.RegisterType<IObjectContext, DbContextAdapter>(new ContainerControlledLifetimeManager());
};
扩展应用
既然有了抽象基类 RepositoryDecorator<T> ,我们可以从其设计衍生多个特定场景的 Repository 。
比如,当我们需要为某个 Table 的 Entity 添加缓存功能时,我们可以定制一个 CachableRepository<T> 来完成这一个扩展。
EntityFramework中使用Repository装饰器的更多相关文章
- Python中利用函数装饰器实现备忘功能
Python中利用函数装饰器实现备忘功能 这篇文章主要介绍了Python中利用函数装饰器实现备忘功能,同时还降到了利用装饰器来检查函数的递归.确保参数传递的正确,需要的朋友可以参考下 " ...
- Angular 个人深究(一)【Angular中的Typescript 装饰器】
Angular 个人深究[Angular中的Typescript 装饰器] 最近进入一个新的前端项目,为了能够更好地了解Angular框架,想到要研究底层代码. 注:本人前端小白一枚,文章旨在记录自己 ...
- python 中多个装饰器的执行顺序
python 中多个装饰器的执行顺序: def wrapper1(f1): print('in wrapper1') def inner1(*args,**kwargs): print('in inn ...
- 第7.17节 Python类中的静态方法装饰器staticmethod 定义的静态方法深入剖析
第7.17节 Python类中的静态方法装饰器staticmethod 定义的静态方法深入剖析 静态方法也是通过类定义的一种方法,一般将不需要访问类属性但是类需要具有的一些能力可以静态方法提供. 一 ...
- 第7.26节 Python中的@property装饰器定义属性访问方法getter、setter、deleter 详解
第7.26节 Python中的@property装饰器定义属性访问方法getter.setter.deleter 详解 一. 引言 Python中的装饰器在前面接触过,老猿还没有深入展开介绍装饰 ...
- Python中的各种装饰器详解
Python装饰器,分两部分,一是装饰器本身的定义,一是被装饰器对象的定义. 一.函数式装饰器:装饰器本身是一个函数. 1.装饰函数:被装饰对象是一个函数 [1]装饰器无参数: a.被装饰对象无参数: ...
- Python中闭包、装饰器的概念
1.闭包(Closure)的概念: 内部函数中对enclosing作用域的变量进行引用 1 passline = 60 2 def func(val): 3 print('%x' % id(val)) ...
- 谈谈Python中的decorator装饰器,如何更优雅的重用代码
众所周知,Python本身有很多优雅的语法,让你能用一行代码写出其他语言很多行代码才能做的事情,比如: 最常用的迭代(eg: for i in range(1,10)), 列表生成式(eg: [ x* ...
- Python 中写一个装饰器实现限制频率访问
1.思路: 首先要在装饰器中确定访问的方法名, 第一次可以访问成功,之后要在规定的时间(变量)之后才可以访问. 初始应该有一个变量为0;访问成功之后把当前的时间赋值给这个变零. 这样再次访问时把当前的 ...
随机推荐
- SHELL脚本攻略(学习笔记)--2.4 find
转载请注明出处:http://www.cnblogs.com/f-ck-need-u/p/5916657.html 超级强大的find命令. find搜索是从磁盘搜索,而不是从数据库搜索. 2.4 ...
- 6.Mybatis中的动态Sql和Sql片段(Mybatis的一个核心)
动态Sql是Mybatis的核心,就是对我们的sql语句进行灵活的操作,他可以通过表达式,对sql语句进行判断,然后对其进行灵活的拼接和组装.可以简单的说成Mybatis中可以动态去的判断需不需要某些 ...
- URL Quoting
[URL Quoting] The URL quoting functions focus on taking program data and making it safe for use as U ...
- jQuery数组处理汇总
jQuery数组处理汇总 有段时间没写什么了, 打算把jquery中的比较常用的数组处理方法汇总一下 $.each(array, [callback])遍历,很常用 1 2 3 4 5 6 7 8 ...
- redis与memcached比较
引用自:http://blog.csdn.net/e_wsq/article/details/23551799 最近需要用no-sql数据库来保存大量的数据,插入和查询都比较频繁,相对而言查询更加频繁 ...
- 初识ASP.NET CORE:二、优劣
Which one is right for me? ASP.NET is a mature web platform that provides all the services that you ...
- android BroadcastReceiver
AndroidManifast.xml <?xml version="1.0" encoding="utf-8"?> <manifest xm ...
- js学习---常用的内置对象(API)小结 :
内置对象(API): 日期 Date: getFullYear() 返回完整的4位的年份 如:2016 getMonth() 返回月份,从0开始 getDate() 返回当前月的第几天,当 ...
- jsp_属性范围_session
session属性设置后,不管是客户端跳转还是服务器端跳转,只要属性设置了就可以取得. 下面写个小例子来验证一下: (1)session_demo.jsp <%@ page contentTyp ...
- UIView的剖析(转)
转自:http://blog.csdn.net/mengtnt/article/details/6716289 前面说过UIViewController,但是UIView也是在MVC中非常重要的一层 ...