1

我正在使用ASP.NET MVC + NHibernate +流利NHibernate和有延遲加載的問題。如何在NHibernate中實現開放會話視圖模式?

通過這個問題(How to fix a NHibernate lazy loading error "no session or session was closed"?),我發現我必須在View模式下實現Open Session,但我不知道如何。

在我的庫類,我用這樣

public ImageGallery GetById(int id) { 
     using(ISession session = NHibernateSessionFactory.OpenSession()) { 
      return session.Get<ImageGallery>(id); 
     } 
    } 

    public void Add(ImageGallery imageGallery) { 
     using(ISession session = NHibernateSessionFactory.OpenSession()) { 
      using(ITransaction transaction = session.BeginTransaction()) { 
       session.Save(imageGallery); 
       transaction.Commit(); 
      } 
     } 
    } 

方法,這是我的會話工廠輔助類:

public class NHibernateSessionFactory { 
    private static ISessionFactory _sessionFactory; 
    private static ISessionFactory SessionFactory { 
     get { 
      if(_sessionFactory == null) { 
       _sessionFactory = Fluently.Configure() 
        .Database(MySQLConfiguration.Standard.ConnectionString(MyConnString)) 
        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<ImageGalleryMap>()) 
        .ExposeConfiguration(c => c.Properties.Add("hbm2ddl.keywords", "none")) 
        .BuildSessionFactory(); 
      } 
      return _sessionFactory; 
     } 
    } 
    public static ISession OpenSession() { 
     return SessionFactory.OpenSession(); 
    } 
} 

有人可以幫助我實現了視圖模式打開會話?

謝謝。

回答

2

這已經問過,但我不記得在哪裏找到它。當你做了以下或類似的事情時,你有你想要的和一些代碼重複作爲獎金在你的存儲庫中減少。

 

public class Repository 
{ 
    private readonly ISession session; 

    public Repository() 
    { 
    session = CurrentSessionContext.CurrentSession(); 
    } 

    public ImageGallery GetById(int id) 
    { 
    return session.Get<ImageGallery>(id); 
    } 

    public void Add(ImageGallery imageGallery) 
    { 
    session.Save(imageGallery); 
    } 
} 

您也可以使用IoC容器和包裝工作,而不是當前會話的上下文的單元管理會話。

+0

謝謝。它工作得很好! – MCardinale 2010-03-26 22:59:14

+0

我建議爲您的存儲庫類使用手動依賴注入。也就是說,將ISession傳入存儲庫的構造函數。 – 2010-03-27 14:30:00

+0

「手動依賴注入」的唯一原因是單元測試。它沒有像解決與自動注入相關的鬆散耦合。 – Paco 2010-03-27 15:14:20

相關問題