当前位置: 移动技术网 > IT编程>软件设计>领域驱动 > Byteart Retail V2 - 基于Entity Framework Code First的领域驱动设计实践案例

Byteart Retail V2 - 基于Entity Framework Code First的领域驱动设计实践案例

2019年04月03日  | 移动技术网IT编程  | 我要评论

在《》一文中,我给出了一个基于entity framework 4.3.1 code first的领域驱动设计实践案例:byteart retail。此案例得到了广大读者朋友的关注,也有很多网友针对案例中的各种实现技术进行提问,我也基本上一一回答了大家的疑问。为了能够更好地演示领域驱动设计在基于microsoft .net技术上的实践,我对byteart retail作了进一步完善,现将改进版的byteart retail案例(简称byteart retail v2)发布于此,供大家参阅。

与上一个版本的byteart retail案例相比,新版本(v2)的演示案例具有以下改进:

  • 中文注释(不断完善中)
  • 已存在数据库的使用
  • 基于unity的wcf per-request lifetime manager
  • 面向特定需求的仓储接口
  • 规约的具体实现
  • 基于unity的aop拦截
  • 使用log4net记录拦截的exception详细信息

在以下部分中会对上述内容作一些简单的介绍。

byteart retail v2案例源代码下载

【单击此处】下载byteart retail案例v2的源代码

部署运行

  1. 解开byteart retail v2的压缩包
  2. 在sql server数据库中,新建一个名为byteartretail的数据库
  3. 运行sql目录下的byteartretail.sql数据库脚本,这将创建与本案例相关的数据表
  4. 在visual studio 2010中打开byteart retail.sln解决方案,打开byteartretail.services项目下的web.config文件
  5. 根据自己的数据库配置情况,更改entity framework所使用的数据库连接字符串,注意启用mars选项

  6. 在byteartretail.services项目下,找到任意一个.svc文件,单击鼠标右键并选择view in browser菜单,这将启动asp.net development server,并在浏览器中打开选中的wcf服务页面

  7. 启动byteartretail.web项目以显示用户界面

注1:在上一个版本(v1)中,由于使用了不正确的数据库初始化策略,导致读者朋友在创建完数据库之后出现entity framework报错的问题(migration数据库不存在的错误)。在v2中,byteartretaildbcontext在初始化数据库时,将不再使用任何初始化策略,这就解决了v1中的上述问题

注2:在用户界面和功能上,v2和v1没有区别

 

v2的功能改进

中文注释(不断完善中)

根据v1一文中网友的反馈意见,从v2开始我将慢慢地使用中文注释代替原来的英文注释,但整个项目的源代码文件比较多,我平时的个人时间也有限,因此没法一次性全部更新完,只能是在今后的版本升级中不断完善。当然,我也会在版本升级的过程中抽空逐步完善当前版本中的注释内容,并更新文章中的下载链接,所以只能希望网友们:请多关照+敬请谅解+欢迎关注。

已存在数据库的使用

v2中更新了byteartretaildbcontextinitializer类型的initialize公共静态方法(该方法位于byteartretail.domain.repository项目、byteartretail.domain.repositories.entityframework命名空间下),在数据库初始化时不使用任何数据库初始化策略,以此实现已存在数据库的使用。这也使得读者朋友能够更为方便地部署和运行本案例程序。

namespace byteartretail.domain.repositories.entityframework
{
    /// <summary>
    /// 表示由byteart retail专用的数据访问上下文初始化器。
    /// </summary>
    public sealed class byteartretaildbcontextinitailizer : dropcreatedatabaseifmodelchanges<byteartretaildbcontext>
    {
        // 请在使用byteartretaildbcontextinitializer作为数据库初始化器(database initializer)时,去除以下代码行
        // 的注释,以便在数据库重建时,相应的sql脚本会被执行。对于已有数据库的情况,请直接注释掉以下代码行。
        //protected override void seed(byteartretaildbcontext context)
        //{
        //    context.database.executesqlcommand("create unique index idx_customer_username on customers(username)");
        //    context.database.executesqlcommand("create unique index idx_customer_email on customers(email)");
        //    context.database.executesqlcommand("create unique index idx_laptop_name on laptops(name)");
        //    base.seed(context);
        //}

        /// <summary>
        /// 执行对数据库的初始化操作。
        /// </summary>
        public static void initialize()
        {
            database.setinitializer<byteartretaildbcontext>(null);
        }
    }
}

基于unity的wcf per-request lifetime manager

此改进来源于在同一个request中保证repositorycontext的一致性问题。在一个wcf操作上下文中,很多情况下application层的任务协调会涉及到多个repository,而这些repository都应该共享同一个repositorycontext,以便所有的操作能通过repositorycontext进行一次提交,完成unit of work。在v1的案例中,application层中每一个需要用到repository的地方,都会使用repositorycontextmanager来确保repositorycontext实例的一致性,而后又会使用repositorycontextmanager.getrepository方法返回针对特定聚合根的仓储实例。这样做虽然确保了repositorycontext实例的一致性,但同时也失去了repository的扩展性:我们只能使用entityframeworkrepository泛型类型的repository实现,而其提供的仓储方法又极为有限。

因此,v2采用基于unity的wcf per-request lifetime manager来解决这样的矛盾。由于wcf服务层是通过unity ioc容器来获得application层的具体实现(表现为servicelocator模式的应用),因此在application层就能够获得由unity通过构造器注入的repositorycontext以及repository的实例,并且此时的repositorycontext的生命周期是由wcf per-request lifetime manager托管的(每次wcf request发起时,resolve一个新的实例,完成wcf request处理后,销毁实例)。我们可以从以下代码片段大致了解到这一点:

/// <summary>
/// 表示与“客户”相关的应用层服务的一种实现。
/// </summary>
public class customerserviceimpl : applicationservice, icustomerservice
{
    #region private fields
    private readonly icustomerrepository customerrepository;
    private readonly ishoppingcartrepository shoppingcartrepository;
    private readonly isalesorderrepository salesorderrepository;
    #endregion

    #region ctor
    /// <summary>
    /// 初始化一个<c>customerserviceimpl</c>类型的实例。
    /// </summary>
    /// <param name="context">用来初始化<c>customerserviceimpl</c>类型的仓储上下文实例。</param>
    /// <param name="customerrepository">“客户”仓储实例。</param>
    /// <param name="shoppingcartrepository">“购物车”仓储实例。</param>
    /// <param name="salesorderrepository">“销售订单”仓储实例。</param>
    public customerserviceimpl(irepositorycontext context,
        icustomerrepository customerrepository,
        ishoppingcartrepository shoppingcartrepository,
        isalesorderrepository salesorderrepository)
        :base(context)
    {
        this.customerrepository = customerrepository;
        this.shoppingcartrepository = shoppingcartrepository;
        this.salesorderrepository = salesorderrepository;
    }
    #endregion

    #region icustomerservice members
    /// <summary>
    /// 根据给定的客户信息,创建客户对象。
    /// </summary>
    /// <param name="dataobject">包含了客户信息的数据传输对象。</param>
    /// <returns>已创建客户对象的全局唯一标识。</returns>
    public guid createcustomer(customerdataobject dataobject)
    {
        if (dataobject == null)
            throw new argumentnullexception("customerdataobject");

        if (customerrepository.usernameexists(dataobject.username))
            throw new domainexception("customer with the username of '{0}' already exists.", dataobject.username);

        if (customerrepository.emailexists(dataobject.email))
            throw new domainexception("customer with the email of '{0}' already exists.", dataobject.email);

        customer customer = mapper.map<customerdataobject, customer>(dataobject);
        shoppingcart shoppingcart = customer.createshoppingcart();

        customerrepository.add(customer);
        shoppingcartrepository.add(shoppingcart);

        context.commit();

        return customer.id;
    }
    
    // ****其它代码部分忽略****
    #endregion
}

 

而在byteartretail.services项目的web.config中,配置irepositorycontext的lifetime manager为wcfperrequestlifetimemanager。wcfperrequestlifetimemanager的具体实现代码可以在byteartretail.infrastructure项目中找到:

<!--repository context & repositories-->
<register type="byteartretail.domain.repositories.irepositorycontext, byteartretail.domain"
      mapto="byteartretail.domain.repositories.entityframework.entityframeworkrepositorycontext, byteartretail.domain.repositories">
  <lifetime type="byteartretail.infrastructure.wcfperrequestlifetimemanager, byteartretail.infrastructure"/>
</register>

 

面向特定需求的仓储接口

由于v2解耦了repositorycontextmanager与repository的具体实现,因此我们可以很方便地自定义面向特定需求的仓储接口。在byteartretail.domain项目的repositories子目录下,新增了类似ixxxrepository(比如:icustomerrepository、isalesorderrepository等)这样的仓储接口,而这些接口又实现了irepository泛型接口。

byteartretail.domain.repositories项目下包含了对这些ixxxrepsitory接口的实现类,这些类不仅实现了ixxxrepository接口,而且继承于entityframeworkrepository泛型类,以便能够直接使用那些已定义的标准仓储操作。在介绍v1一文的评论部分,有朋友提出,如果需要按多个实体属性进行排序,标准的仓储接口应该如何操作。在v2中,laptoprepository的getalllaptops方法给出了答案:

public ienumerable<laptop> getalllaptops()
{
    var query = efcontext.context.set<laptop>()
        .orderby(l => l.unitprice)
        .thenby(l => l.name);
    return query.tolist();
}

 

这种实现方式的另一个好处是,当今后我发现需要用其它的字段进行排序时,我可以重新实现ilaptoprepository接口,并在实现类中处理排序问题,而不需要去修改laptoprepository类甚至是ilaptoprepository接口以使其提供其它字段的排序功能。

规约的具体实现

在v1的源代码中,所有传递给repository的规约都是通过specification泛型类的eval方法,通过传入lambda表达式而产生的。在v2中,这些代码都被规约的具体实现所取代:我们可以在byteartretail.domain.repositories项目的specifications目录下找到这些实现类。

从表面上看,使用eval会更方便编程,而且规约的具体实现本质上也是lambda表达式。而实际上,这样的改动是基于以下几点考虑:

  1. 规约的具体实现的类名明确地表示了规约的动机,这样有利于将规约作为通用语言的一个元素而参与到面向领域的讨论中
  2. 面向对象的规约实现有助于模式应用,可以进一步考察实现仓储动态查询的可行性

基于unity的aop拦截

v2使用了unity的一个扩展(extension)来实现aop拦截。该扩展名为unity interception extension,可以在nuget package manager中找到。需要使用unity拦截功能的项目,不仅要添加对unity的引用,而且还需要添加对unity interception extension的引用。

为了演示aop拦截,v2定义了一个拦截行为:exceptionloggingbehavior,用于在application层发生异常时,将异常信息写入日志文件。此拦截行为的源代码位于byteartretail.infrastructure项目的inteceptionbehaviors目录下,在invoke方法中使用utils工具类处理捕获的异常。

在byteartretail.services项目的web.config文件里,当注册unity容器时,我们需要针对application层的接口类型指定拦截器类型以及拦截行为:

<register type="byteartretail.application.icustomerservice, byteartretail.application"
          mapto="byteartretail.application.implementation.customerserviceimpl, byteartretail.application">
  <interceptor type="interfaceinterceptor"/>
  <interceptionbehavior 
    type="byteartretail.infrastructure.interceptionbehaviors.exceptionloggingbehavior, byteartretail.infrastructure"/>
</register>

 

使用log4net记录拦截的exception详细信息

v2结合unity的aop拦截,使用log4net记录由application层产生的异常信息,大致有以下几点需要注意:

  1. 在byteartretail.services项目的assemblyinfo.cs文件中,指定log4net的配置源:
    [assembly: log4net.config.xmlconfigurator(watch = true)]
  2. 在byteartretail.services项目的global.asax.cs文件中,初始化log4net框架:
    protected void application_start(object sender, eventargs e)
    {
        byteartretaildbcontextinitailizer.initialize();
        applicationservice.initialize();
        log4net.config.xmlconfigurator.configure();
    }

  3. 在byteartretail.services项目的web.config中,配置log4net。详情请见此文件

下图是在byteartretail.services\logs目录下产生的日志信息:

 

总结

本文简要介绍了基于entity framework code first的领域驱动设计案例:byteart retail的v2版本的一些改动和新特性,读者朋友可以使用文中提供的链接下载v2的源代码,如有疑问和建议,欢迎留言回复。在下一个版本的byteart retail中,我将继续研究领域事件的派发、enterprise service bus(esb)以及系统集成和防腐层等相关专题。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网