EntityFramework之領域驅動設計實踐(九)

倉儲的實現:深入篇

早在年前的時候就已經在CSAI博客發表了上一篇文章:《倉儲的實現:基礎篇》。苦於日夜奔波於工作與生活之間,一直沒有能夠抽空繼續探討倉儲的實現細節,也讓很多關注EntityFramework和領域驅動設計的朋友們備感失望。

閒話不多說,現在繼續考慮,如何讓倉儲的操作在相同的事物處理上下文中進行。DDD引入倉儲模式,其目的之一就是能夠通過倉儲隱藏對象持久化的技術細節,使得領域模型變得更爲“純淨”。由此可見,倉儲的實現是需要基礎結構層的組件支持的,表現爲對數據庫的操作。在傳統的關係型數據庫操作中,事務處理是一個很重要的概念,雖然從目前某些大型項目看,事務處理會降低效率,但它保證了數據的完整性。關係型數據庫仍然是目前數據持久化機制的主流,事務處理的實現還是很有必要的。

爲了迎合倉儲模式,就需要對經典的ObjectContext使用方式作一些調整。比如,原本我們可以非常簡單地使用using (EntitiesContainer ec = new EntitiesContainer())語句來界定LINQ to Entities的操作範圍,並使用ObjectContext的SaveChanges成員方法提交事務,而在引入了倉儲的實現中,就不能繼續採用這種經典的使用方式。這讓EntityFramework看上去變得很奇怪,也很牽強,我相信很多網友會批評我的做法,因爲我把問題複雜化了。

其實,這應該是關注點不同罷了。關注EntityFramework的開發人員,自然覺得經典的調用方式簡單明瞭,而從DDD的角度看呢?只能把關注點放在倉儲上,而把EntityFramework當成是倉儲的一種技術選型(當然從DDD角度講,我們完全可以不選擇EntityFramework,而去選擇其它技術)。所以本文暫且拋開EntityFramework,繼續在上文的基礎上,討論倉儲的實現。

前面提到,倉儲的實現需要考慮事務處理,而且根據DDD的經驗,針對每一個聚合根,都需要有個倉儲對其進行持久化以及對象重新組裝等操作。爲此,我的想法是,將倉儲操作“界定”在某一個事務處理上下文(Context)中,倉儲的實例是由Context獲得的,這有點像EntityFramework中ObjectContext與EntityObject的關係那樣。由於倉儲是來自於transaction context,所以它知道目前處於哪個事務上下文中。我定義的這個transaction context如下:

隱藏行號 複製代碼 Transaction Context
  1. public interface IRepositoryTransactionContext : IDisposable
    
  2. {
    
  3.     IRepository<TEntity> GetRepository<TEntity>()
    
  4.         where TEntity : EntityObject, IAggregateRoot;
    
  5.     void BeginTransaction();
    
  6.     void Commit();
    
  7.     void Rollback();
    
  8. }
    
  9. 
    

上面第三行代碼定義了一個接口方法,這個方法的主要作用就是返回一個針對指定聚合根實體的倉儲實例。剩下那三行代碼就很明顯了,那是標準的transaction操作:啓動事務、提交事務以及回滾事務。

在設計上,可以根據需要,選擇合適的技術來實現IRepositoryTransactionContext。我們現在討論的是EntityFramework,所以我將給出EntityFramework的具體實現。當然,如果你不選用EntityFramework,而是用NHibernate實現數據持久化,這樣的設計同樣能夠使你達到目的。以下是基於EntityFramework的實現:EdmRepositoryTransactionContext的僞代碼。

隱藏行號 複製代碼 EdmRepositoryTransactionContext
  1. internal class EdmRepositoryTransactionContext : IRepositoryTransactionContext
    
  2. {
    
  3.     private ObjectContext objContext;
    
  4.     private Dictionary<Type, object> repositoryCache = new Dictionary<Type, object>();
    
  5. 
    
  6.     public EdmRepositoryTransactionContext(ObjectContext objContext)
    
  7.     {
    
  8.         this.objContext = objContext;
    
  9.     }
    
  10. 
    
  11.     #region IRepositoryTransactionContext Members
    
  12. 
    
  13.     public IRepository<TEntity> GetRepository<TEntity>() where TEntity : EntityObject, IAggregateRoot
    
  14.     {
    
  15.         if (repositoryCache.ContainsKey(typeof(TEntity)))
    
  16.         {
    
  17.             return (IRepository<TEntity>)repositoryCache[typeof(TEntity)];
    
  18.         }
    
  19.         IRepository<TEntity> repository = new EdmRepository<TEntity>(this.objContext);
    
  20.         this.repositoryCache.Add(typeof(TEntity), repository);
    
  21.         return repository;
    
  22.     }
    
  23. 
    
  24.     public void BeginTransaction() 
    
  25.     { 
    
  26.         // We do not need to begin a transaction here because the object context,
    
  27.         // which would handle the transaction, was created and injected into the
    
  28.         // constructor by Castle Windsor framework.
    
  29.     }
    
  30. 
    
  31.     public void Commit()
    
  32.     {
    
  33.         this.objContext.SaveChanges();
    
  34.     }
    
  35. 
    
  36.     public void Rollback()
    
  37.     {
    
  38.         // We also do not need to perform the rollback operation because
    
  39.         // entity framework will handle this for us, just when the execution
    
  40.         // point is stepping out of the using scope.
    
  41.     }
    
  42. 
    
  43.     #endregion
    
  44. 
    
  45.     #region IDisposable Members
    
  46. 
    
  47.     public void Dispose()
    
  48.     {
    
  49.         this.repositoryCache.Clear();
    
  50.         this.objContext.Dispose();
    
  51.     }
    
  52. 
    
  53.     #endregion
    
  54. }
    
  55. 
    

EdmRepositoryTransactionContext被定義爲internal,這個設計是合理的,因爲Domain層是不需要知道事務上下文的具體實現,它將會被IoC/DI容器注入到Domain層中(本系列文章採用Castle Windsor框架)。在EdmRepositoryTransactionContext的構造函數中,它需要EntityFramework的ObjectContext對象來初始化實例。同樣,由於IoC/DI的使用,我們在代碼中也是不需要去創建這個ObjectContext的,交給Castle Windsor就OK了。第13行的GetRepository方法簡單地採用了Dictionary對象來實現緩存倉儲實例的效果,當然這種做法還有待改進。

EdmRepositoryTransactionContext是不需要BeginTransaction的,我們將方法置空,因爲EntityFramework的事務會由ObjectContext來管理,同理,Rollback也被置空。

EdmRepository的實現就比較顯而易見了,請參見上文。

此外,我們還可以針對NHibernate實現倉儲模式,只需要實現IRepositoryTransactionContext和IRepository接口即可,比如:

隱藏行號 複製代碼 NHibernateRepositoryTransactionContext實現
  1. internal class NHibernateRepositoryTransactionContext : IRepositoryTransactionContext
    
  2. {
    
  3.     ITransaction transaction;
    
  4.     Dictionary<Type, object> repositoryCache = new Dictionary<Type, object>();
    
  5. 
    
  6.     public ISession Session { get { return DatabaseSessionFactory.Instance.Session; } }
    
  7. 
    
  8.     #region IRepositoryTransactionContext Members
    
  9. 
    
  10.     public IRepository<TEntity> GetRepository<TEntity>() 
    
  11.         where TEntity : EntityObject, IAggregateRoot
    
  12.     {
    
  13.         if (repositoryCache.ContainsKey(typeof(TEntity)))
    
  14.         {
    
  15.             return (IRepository<TEntity>)repositoryCache[typeof(TEntity)];
    
  16.         }
    
  17.         IRepository<TEntity> repository = new NHibernateRepository<TEntity>(this.Session);
    
  18.         this.repositoryCache.Add(typeof(TEntity), repository);
    
  19.         return repository;
    
  20.     }
    
  21. 
    
  22.     public void BeginTransaction()
    
  23.     {
    
  24.         transaction = DatabaseSessionFactory.Instance.Session.BeginTransaction();
    
  25.     }
    
  26. 
    
  27.     public void Commit()
    
  28.     {
    
  29.         transaction.Commit();
    
  30.     }
    
  31. 
    
  32.     public void Rollback()
    
  33.     {
    
  34.         transaction.Rollback();
    
  35.     }
    
  36. 
    
  37.     #endregion
    
  38. 
    
  39.     #region IDisposable Members
    
  40. 
    
  41.     public void Dispose()
    
  42.     {
    
  43.         transaction.Dispose();
    
  44.         ISession dbSession = DatabaseSessionFactory.Instance.Session;
    
  45.         if (dbSession != null && dbSession.IsOpen)
    
  46.             dbSession.Close();
    
  47.     }
    
  48. 
    
  49.     #endregion
    
  50. }
    
  51. 
    
隱藏行號 複製代碼 NHibernateRepository實現
  1. internal class NHibernateRepository<TEntity> : IRepository<TEntity>
    
  2.     where TEntity : EntityObject, IAggregateRoot
    
  3. {
    
  4.     ISession session;
    
  5. 
    
  6.     public NHibernateRepository(ISession session)
    
  7.     {
    
  8.         this.session = session;
    
  9.     }
    
  10. 
    
  11.     #region IRepository<TEntity> Members
    
  12. 
    
  13.     public void Add(TEntity entity)
    
  14.     {
    
  15.         this.session.Save(entity);
    
  16.     }
    
  17. 
    
  18.     public TEntity GetByKey(int id)
    
  19.     {
    
  20.         return (TEntity)this.session.Get(typeof(TEntity), id);
    
  21.     }
    
  22. 
    
  23.     public IEnumerable<TEntity> FindBySpecification(Func<TEntity, bool> spec)
    
  24.     {
    
  25.         throw new NotImplementedException();
    
  26.     }
    
  27. 
    
  28.     public void Remove(TEntity entity)
    
  29.     {
    
  30.         this.session.Delete(entity);
    
  31.     }
    
  32. 
    
  33.     public void Update(TEntity entity)
    
  34.     {
    
  35.         this.session.SaveOrUpdate(entity);
    
  36.     }
    
  37. 
    
  38.     #endregion
    
  39. }
    
  40. 
    

在NHibernateRepositoryTransactionContext中使用了一個DatabaseSessionFactory的類,該類主要用於管理NHibernate的Session對象,具體實現如下(該實現已被用於我的Apworks應用開發框架原型中):

隱藏行號 複製代碼 DatabaseSessionFactory實現
  1. /// <summary>
    
  2. /// Represents the factory singleton for database session.
    
  3. /// </summary>
    
  4. internal sealed class DatabaseSessionFactory
    
  5. {
    
  6.     #region Private Static Fields
    
  7.     /// <summary>
    
  8.     /// The singleton instance of the database session factory.
    
  9.     /// </summary>
    
  10.     private static readonly DatabaseSessionFactory databaseSessionFactory = new DatabaseSessionFactory();
    
  11.     #endregion
    
  12. 
    
  13.     #region Private Fields
    
  14.     /// <summary>
    
  15.     /// The session factory instance.
    
  16.     /// </summary>
    
  17.     private ISessionFactory sessionFactory = null;
    
  18.     /// <summary>
    
  19.     /// The session instance.
    
  20.     /// </summary>
    
  21.     private ISession session = null;
    
  22.     #endregion
    
  23. 
    
  24.     #region Constructors
    
  25.     /// <summary>
    
  26.     /// Privately constructs the database session factory instance, configures the
    
  27.     /// NHibernate framework by using the assemblies listed in the configured spaces(paths)
    
  28.     /// that are decorated by <see cref="EntityVisibleAttribute"/>.
    
  29.     /// </summary>
    
  30.     private DatabaseSessionFactory()
    
  31.     {
    
  32.         Configuration nhibernateConfig = new Configuration();
    
  33.         nhibernateConfig.Configure();
    
  34.         nhibernateConfig.AddAssembly(typeof(IAggregateRoot).Assembly);
    
  35.         sessionFactory = nhibernateConfig.BuildSessionFactory();
    
  36.     }
    
  37.     #endregion
    
  38. 
    
  39.     #region Public Properties
    
  40.     /// <summary>
    
  41.     /// Gets the singleton instance of the database session factory.
    
  42.     /// </summary>
    
  43.     public static DatabaseSessionFactory Instance
    
  44.     {
    
  45.         get
    
  46.         {
    
  47.             return databaseSessionFactory;
    
  48.         }
    
  49.     }
    
  50. 
    
  51.     /// <summary>
    
  52.     /// Gets the singleton instance of the session. If the session has not been
    
  53.     /// initialized or opened, it will return a newly opened session from the session factory.
    
  54.     /// </summary>
    
  55.     public ISession Session
    
  56.     {
    
  57.         get
    
  58.         {
    
  59.             ISession result = session;
    
  60.             if (result != null && result.IsOpen)
    
  61.                 return result;
    
  62.             return OpenSession();
    
  63.         }
    
  64.     }
    
  65.     #endregion
    
  66. 
    
  67.     #region Public Methods
    
  68.     /// <summary>
    
  69.     /// Always opens a new session from the session factory.
    
  70.     /// </summary>
    
  71.     /// <returns>The newly opened session.</returns>
    
  72.     public ISession OpenSession()
    
  73.     {
    
  74.         this.session = sessionFactory.OpenSession();
    
  75.         return this.session;
    
  76.     }
    
  77.     #endregion
    
  78. 
    
  79. }
    
  80. 
    

簡單小結一下。通過上面的例子可以看到,倉儲的實現是不能依賴於任何技術細節的,因爲領域模型並不關心技術問題。這並不是DDD一書中怎麼說,我們就得怎麼做。事實上的確如此,因爲DDD的思想,使得我們應該把關注點放在業務分析與領域建模上,而倉儲實現的分離正是這一思想的具體表現形式。不管怎麼樣,採用其它的手段也罷,我們還是應該遵循“將關注點放在領域”這一宗旨。

接下來看如何在領域層結合IoC框架使用倉儲。仍然以Castle Windsor爲例。配置文件如下(超長部分我用省略號去掉了):

 

隱藏行號 複製代碼 Castle Windsor配置
  1. <castle>
    
  2.   <components>
    
  3.     <!-- Object Context for Entity Data Model -->
    
  4.     <component id="ObjectContext"
    
  5.                service="System.Data.Objects.ObjectContext, System.Data.Entity, Version=4.0.0.0,......" 
    
  6.                type="EasyCommerce.Domain.Model.EntitiesContainer, EasyCommerce.Domain"/>
    
  7. 
    
  8.     <component id="GeneralRepository"
    
  9.                service="EasyCommerce.Domain.IRepository`1[[EasyCommerce.Domain.Model.Customer, ......"
    
  10.                type="EasyCommerce.Infrastructure.Repositories.EdmRepositories.EdmRepository`1[[EasyCo......">
    
  11.       <objContext>${ObjectContext}</objContext>
    
  12.     </component>
    
  13. 
    
  14.     <component id="TransactionContext"
    
  15.                service="EasyCommerce.Domain.IRepositoryTransactionContext, EasyCommerce.Domain......"
    
  16.                type="EasyCommerce.Infrastructure.Repositories.EdmRepositories.EdmRepositoryTransactionContext, ...">
    
  17.     </component>
    
  18. 
    
  19.   </components>
    
  20. </castle>
    
  21. 
    

以下是調用代碼:

隱藏行號 複製代碼 調用方代碼
  1. [TestMethod]
    
  2. public void TestCreateCustomer()
    
  3. {
    
  4.     IWindsorContainer container = new WindsorContainer(new XmlInterpreter());
    
  5.     using (IRepositoryTransactionContext tx = container.GetService<IRepositoryTransactionContext>())
    
  6.     {
    
  7.         tx.BeginTransaction();
    
  8.         try
    
  9.         {
    
  10.             Customer customer = Customer.CreateCustomer("daxnet", "12345",
    
  11.                 new Name { FirstName = "Sunny", LastName = "Chen" },
    
  12.                 new Address(), new Address(), DateTime.Now.AddYears(-29));
    
  13. 
    
  14.             IRepository<Customer> customerRepository = tx.GetRepository<Customer>();
    
  15.             customerRepository.Add(customer);
    
  16. 
    
  17.             tx.Commit();
    
  18.         }
    
  19.         catch
    
  20.         {
    
  21.             tx.Rollback();
    
  22.             throw;
    
  23.         }
    
  24.     }
    
  25. }
    
  26. 
    

 

測試結果及數據庫數據結果:

image

 

image

 

注意】:在使用NHibernate的倉儲實現時,由於NHibernate的延遲加載特性,需要將實體的屬性設置爲virtual,以便由NHibernate產生Proxy Class進而實現延遲加載;但是由EntityFramework自動生成的源代碼並不會將實體屬性設置爲virtual,而採用partial class也無法解決這個問題。因此需要在代碼生成技術上做文章。我的做法是,針對edmx產生一個基於T4的代碼生成模板,然後修改這個模板,分別在WritePrimitiveTypeProperty和WriteComplexTypeProperty方法中的適當位置加上virtual關鍵字:

隱藏行號 複製代碼 WritePrimitiveTypeProperty
  1.     private void WritePrimitiveTypeProperty(EdmProperty primitiveProperty, CodeGenerationTools code)
    
  2.     {
    
  3.         MetadataTools ef = new MetadataTools(this);
    
  4. #>
    
  5. 
    
  6.     /// <summary>
    
  7.     /// <#=SummaryComment(primitiveProperty)#>
    
  8.     /// </summary><#=LongDescriptionCommentElement(primitiveProperty, 1)#>
    
  9.     [EdmScalarPropertyAttribute(EntityKeyProperty=<#=code.CreateLiteral(ef.IsKey(primitiveProperty))#>, 
  10. IsNullable=<#=code.CreateLiteral(ef.IsNullable(primitiveProperty))#>)]
    
  11.     [DataMemberAttribute()]
    
  12.     <#=code.SpaceAfter(NewModifier(primitiveProperty))#><#=Accessibility.ForProperty(primitiveProperty)#> virtual
  13.  <#=code.Escape(primitiveProperty.TypeUsage)#> <#=code.Escape(primitiveProperty)#>
    
  14.     {
    
  15.         <#=code.SpaceAfter(Accessibility.ForGetter(primitiveProperty))#>get
    
  16.         {
    
  17. <#+             if (ef.ClrType(primitiveProperty.TypeUsage) == typeof(byte[]))
    
  18.                 {
    
  19. #>
    
  20.             return StructuralObject.GetValidValue(<#=code.FieldName(primitiveProperty)#>);
    
  21. 
    
隱藏行號 複製代碼 WriteComplexTypeProperty
  1.     private void WriteComplexTypeProperty(EdmProperty complexProperty, CodeGenerationTools code)
    
  2.     {
    
  3. #>
    
  4. 
    
  5.     /// <summary>
    
  6.     /// <#=SummaryComment(complexProperty)#>
    
  7.     /// </summary><#=LongDescriptionCommentElement(complexProperty, 1)#>
    
  8.     [EdmComplexPropertyAttribute()]
    
  9.     [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    
  10.     [XmlElement(IsNullable=true)]
    
  11.     [SoapElement(IsNullable=true)]
    
  12.     [DataMemberAttribute()]
    
  13.     <#=code.SpaceAfter(NewModifier(complexProperty))#><#=Accessibility.ForProperty(complexProperty)#> virtual 
  14. <#=MultiSchemaEscape(complexProperty.TypeUsage, code)#><#=code.Escape(complexProperty)#>
    
  15.     {
    
  16.         <#=code.SpaceAfter(Accessibility.ForGetter(complexProperty))#>get
    
  17.         {
    
  18.             <#=code.FieldName(complexProperty)#> = GetValidValue(<#=code.FieldName(complexProperty)#>, 
  19. "<#=complexProperty.Name#>", 
  20. false, <#=InitializedTrackingField(complexProperty, code)#>);
    
  21.             <#=InitializedTrackingField(complexProperty, code)#> = true;
    
  22. 
    

始終堅持一個原則:不要在生成的代碼上直接修改,一是工作量巨大,另一方面就是,代碼是自動生成的,今後模型修改了,代碼將會重新生成。

出自:http://www.cnblogs.com/daxnet/archive/2010/07/10/1774706.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章