2010-12-07 53 views
6

我使用流利NHibernate,我喜歡它! 我有一個小問題:啓動時間大約是10秒,我不知道如何優化Fluent nHibernate 爲了使啓動時間更少問題,我把它放在一個線程上。流利的nHibernate慢啓動時間

有人可以告訴解決這個問題嗎?並修改下面的代碼以改善性能以改善性能?

我看到這樣的: http://nhforge.org/blogs/nhibernate/archive/2009/03/13/an-improvement-on-sessionfactory-initialization.aspx 但我不知道如何使這與Fluent nHibernate一起工作。

我的代碼是這樣的:

public static ISession ObterSessao()   
{ 
     System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest; 

     string ConnectionString = ConfigurationHelper.LeConfiguracaoWeb("EstoqueDBNet"); // My Connection string goes here 

     var config = Fluently.Configure() 
      .Database(FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard.ConnectionString(ConnectionString)); 

     config.Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())); 

     var session = config 
      .BuildSessionFactory() 
      .OpenSession(); 

     System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Normal; 

     return session; 
    } 

回答

2

菲爾有正確的答案,但把它遠一點看看http://nhibernate.info/blog/2009/03/13/an-improvement-on-sessionfactory-initialization.html用於將NHibernate配置序列化到一個文件中,所以每次啓動應用程序時都不必重新編譯它。根據各種因素(主要是你有的映射數量),這可能會也可能不會快一點(依據這個數字),Is there any data on NHibernate vs Fluent NHibernate startup performance?

只是爲了強調(根據你在回答評論中的一些後續問題),你應該序列化(NHibernate.Cfg。)配置對象,而不是SessionFactory。

然後,使用Fluently.Configure(Configuration cfg)重載創建FluentConfiguration時注入配置(而不是自動爲您創建一個配置)。

5

你只需要一次生成配置。目前,您每次獲得會話時都會構建新配置。

+1

嗨,我怎麼能將配置對象存儲在一個文件,所以當我再次運行我的程序時,我可以讀取它(反序列化)並快速啓動程序?我嘗試在上面的代碼中序列化配置對象,但它只返回了這個:<?xml version =「1.0」?> Tony 2010-12-08 00:12:22

+0

您可以將代碼放入靜態構造函數中,並將SessionFactory分配給返回ISessionFactory的靜態屬性。然後調用obtersesao.OpenSession() – Phill 2010-12-08 00:20:59

+0

有沒有辦法將工廠存儲(序列化)在一個文件中,並在稍後恢復?由於我的應用程序是一個可執行文件,每次用戶運行它時,都會有10秒的延遲。 – Tony 2010-12-08 01:15:19

2

首先,不要混淆線程的優先級,如果有什麼你正在做的事情會讓它變慢。其次,就像Phill說的那樣,你需要緩存你的SessionFactory,或者每當你需要一個會話對象時你都要重新配置這個配置。

你可以做這樣的事情,還是在if代碼移動到類的靜態構造函數:

private static SessionFactory _factory = null; 
public static ISession ObterSessao()   
{ 
    if(_factory == null) { 
     string ConnectionString = ConfigurationHelper.LeConfiguracaoWeb("EstoqueDBNet"); // My Connection string goes here 

     var config = Fluently.Configure() 
      .Database(FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard.ConnectionString(ConnectionString)); 

     config.Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())); 

     _factory = config.BuildSessionFactory(); 
    } 

    return _factory.OpenSession(); 
}