上一讲介绍了,并提到下次要讲Unity,所以这篇文章当然就要介绍它了,呵呵,Unity是Microsoft.Practices中的一部分,主要实现了依赖注入的功能,或者叫它控制反转,对于控制反转(IoC)的文章我介绍了不少,,等等,今天主要说一下Unity!
在我的DDD架构项目中,各层间实现IoC使用的是Unity,因为考虑到AOP,cache等功能,所以就直接用Microsoft.Practices组件了,它真的很强大!这次的项目在业务上采用WCF实现,所以WCF业务与基础设施之间会有通信,而基础设施只是去实现Domain定义的功能,所以这两个层之间也会有通信,最后就是Domain与WCF之间同样存在着接口的通信,如图:
Domain层定义一个接口,部分代码如下:
////// 获取产品列表 /// ///IQueryable GetProduct();
基础设施层实现它
public IQueryableGetProduct() { return this.GetModel(); }
它们之间的通信不存在IoC,因为如果你要使用其它的持久化方法,可以再建立一个项目,以别一种方式去实现持久化
WCF去声明一个Domain层的接口,实例化它的基础设施层的实例,这个过程需要解耦合,我们使用Unity来实现,它需要我们在config中去定义如何去实例化。
public class ProductServiceImpl : IProductService { private readonly IProductRepository _productRepository; ////// 构造方法注入 /// /// public ProductServiceImpl(IProductRepository productRepository) { if (productRepository == (IProductRepository)null) throw new ArgumentException("context can't is null."); _productRepository = productRepository; } #region IProductService 成员 public ProductDTO GetProductByID(int id) { Mapper.CreateMap(); return Mapper.Map (_productRepository.Find(id)); }}
上面使用unity中的构造方法注入,我们还可以使用服务调度器进行注入,看这种代码
public class ProductService : ServiceBase, IProductService { //通过ServiceLocator从IoC容器中获得对象 IProductService _productService = ServiceLocator.Instance.GetService(); #region IProductService 成员 public ProductDTO GetProductByID(int id) { return _productService.GetProductByID(id); } }
下面是配置文件中需要注入的代码片断,包括缓存模块和日志模块
好了,对于Unity在DDD中的使用就介绍到这里,如有不清楚的地方,可以直接给我留言或发email!