我有实现测试应用程序。它使用流畅的nhibernate映射到mssql db中的db对象。由于我想学习微调nhib。 mvc3应用程序,我正在使用此应用程序。出于测试目的,只有一个简单的实体具有10个枚举属性和一个字符串属性。
因此,这确实是光波,但是根据nhibernate profiler的启动时间为4.37秒。对于呈现带有几行已选中/未选中属性的实体,这确实很慢。

代码如下。
Domain.SessionProvider.cs

public static ISessionFactory CreateSessionFactory()
{
   var config = Fluently.Configure()
          .Database(MsSqlConfiguration.MsSql2008
          .ConnectionString(c => c.FromConnectionStringWithKey("myConnection")))
          .Mappings(m => m.FluentMappings.Add<FeaturesMap>())
          .ExposeConfiguration(p => p.SetProperty("current_session_context_class", "web"))
          .BuildConfiguration();

          return config.BuildSessionFactory();
}

Global.asax
public class MvcApplication : System.Web.HttpApplication
{
   //SessionPerWebRequest is ommited here as well as other content
   public static ISessionFactory SessionFactory =
               SessionProvider.CreateSessionFactory();

    protected void Application_Start()
    {
       SessionFactory.OpenSession();
    }
}

在myController内部,我有以下内容:
public ActionResult Index()
{
   return View(GetData());
}

private IList<FeaturesViewModel> GetData()
{
     List<Features> data;
     using (ISession session = MvcApplication.SessionFactory.GetCurrentSession())
     {
          using (ITransaction tx = session.BeginTransaction())
          {
              data = session.Query<Features>().Take(5).ToList();
              tx.Commit();

              var viewModelData = FeaturesViewModel.FromDomainModel(data);
              return viewModelData;
           }
      }
}

最佳答案

您可以通过缓存配置来缩短(Web和Windows应用程序的)启动时间。以下类(class)将完成这项工作:

using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Web;
using NHibernate.Cfg;

namespace NH32AutoMap.Core
{
    public class ConfigurationFileCache
    {
        private readonly string _cacheFile;
        private readonly Assembly _definitionsAssembly;

        public ConfigurationFileCache(Assembly definitionsAssembly)
        {
            _definitionsAssembly = definitionsAssembly;
            _cacheFile = "nh.cfg";
            if (HttpContext.Current != null) //for the web apps
                _cacheFile = HttpContext.Current.Server.MapPath(
                                string.Format("~/App_Data/{0}", _cacheFile)
                                );
        }

        public void DeleteCacheFile()
        {
            if (File.Exists(_cacheFile))
                File.Delete(_cacheFile);
        }

        public bool IsConfigurationFileValid
        {
            get
            {
                if (!File.Exists(_cacheFile))
                    return false;
                var configInfo = new FileInfo(_cacheFile);
                var asmInfo = new FileInfo(_definitionsAssembly.Location);

                if (configInfo.Length < 5 * 1024)
                    return false;

                return configInfo.LastWriteTime >= asmInfo.LastWriteTime;
            }
        }

        public void SaveConfigurationToFile(Configuration configuration)
        {
            using (var file = File.Open(_cacheFile, FileMode.Create))
            {
                var bf = new BinaryFormatter();
                bf.Serialize(file, configuration);
            }
        }

        public Configuration LoadConfigurationFromFile()
        {
            if (!IsConfigurationFileValid)
                return null;

            using (var file = File.Open(_cacheFile, FileMode.Open, FileAccess.Read))
            {
                var bf = new BinaryFormatter();
                return bf.Deserialize(file) as Configuration;
            }
        }
    }
}

要使用它
private Configuration readConfigFromCacheFileOrBuildIt()
{
    Configuration nhConfigurationCache;
    var nhCfgCache = new ConfigurationFileCache(MappingsAssembly);
    var cachedCfg = nhCfgCache.LoadConfigurationFromFile();
    if (cachedCfg == null)
    {
        nhConfigurationCache = buildConfiguration();
        nhCfgCache.SaveConfigurationToFile(nhConfigurationCache);
    }
    else
    {
        nhConfigurationCache = cachedCfg;
    }
    return nhConfigurationCache;
}

然后,在调用BuildSessionFactory之前,我们可以从缓存中读取配置文件,或者如果映射已更改,请对其进行构建并再次对其进行缓存:
public ISessionFactory SetUpSessionFactory()
{
    var config = readConfigFromCacheFileOrBuildIt();
    var sessionFactory = config.BuildSessionFactory();

在这里,您可以找到完整的示例:(^)。
+如果要使其工作,请将域类和映射定义程序集与主应用程序的程序集分开(因为如果映射定义程序集比高速缓存文件的LastWriteTime更新,则ConfigurationFileCache类将删除高速缓存文件)。

10-04 23:03