Nhibernate 3.0 cookbook学习笔记 减少程序启动时间
加载NHibernate的配置配制文件要花费相当的时间,NHibernate要加载,解析,编译我们的映射文件和反射对应的模型。
下面来说说如何减少程序在这方面的启动时间。
using System; using System.Configuration; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; using Configuration = NHibernate.Cfg.Configuration; using System.IO; namespace ConfigByAppConfig { public class ConfigurationBuilder { private const string SERIALIZED_CFG="configuration.bin"; public Configuration Build() { Configuration cfg = LoadConfigurationFromFile(); if (cfg == null) { cfg = new Configuration().Configure(); SaveConfigurationToFile(cfg); } return cfg; } /// <summary> /// 将映射文件序列化 /// </summary> /// <param name="cfg"></param> private void SaveConfigurationToFile(Configuration cfg) { using (var file = File.Open(SERIALIZED_CFG, FileMode.Create)) { var bf = new BinaryFormatter(); bf.Serialize(file, cfg); } } /// <summary> /// 加载映射文件,先判断映射文件是不是最新的 /// </summary> /// <returns></returns> private Configuration LoadConfigurationFromFile() { if (!IsConfigurationFileValid()) return null; try { using (var file = File.Open(SERIALIZED_CFG, FileMode.Open)) { var bf = new BinaryFormatter(); return bf.Deserialize(file) as Configuration; } } catch (Exception) { // Something went wrong // Just build a new one return null; } } /// <summary> /// 判断程序有没有改动,如果有返回false,即再重新序列化(一个是判断应用程序,一个是判断配置文件) /// 如果没有,则返回true,即加载以前序列化的文件 /// </summary> /// <returns></returns> private bool IsConfigurationFileValid() { // If we don't have a cached config, // force a new one to be built if (!File.Exists(SERIALIZED_CFG)) return false; var configInfo = new FileInfo(SERIALIZED_CFG); var asm = Assembly.GetExecutingAssembly(); if (asm.Location == null) return false; // If the assembly is newer, // the serialized config is stale var asmInfo = new FileInfo(asm.Location); if (asmInfo.LastWriteTime > configInfo.LastWriteTime) return false; // If the app.config is newer, // the serialized config is stale var appDomain = AppDomain.CurrentDomain; var appConfigPath = appDomain.SetupInformation. ConfigurationFile; var appConfigInfo = new FileInfo(appConfigPath); if (appConfigInfo.LastWriteTime > configInfo.LastWriteTime) return false; // It's still fresh return true; } } }
这个很适合我们要经常启动NH应该程序的环境中,比如开发或测试的时候,也很适合基于WinForm的项目。但对于B/S就不那么适用了,因为往往B/S中应用程序只启动一次。
如果我的文章对你有帮助,就点一下推荐吧.(*^__^*)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步