加載NHibernate的配置配制文件要花費(fèi)相當(dāng)?shù)臅r(shí)間,NHibernate要加載,解析,編譯我們的映射文件和反射對(duì)應(yīng)的模型。
成都創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供東方網(wǎng)站建設(shè)、東方做網(wǎng)站、東方網(wǎng)站設(shè)計(jì)、東方網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁(yè)設(shè)計(jì)與制作、東方企業(yè)網(wǎng)站模板建站服務(wù),10年東方做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。下面來(lái)說(shuō)說(shuō)如何減少程序在這方面的啟動(dòng)時(shí)間。
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;
}
/// /// 將映射文件序列化
/// /// private void SaveConfigurationToFile(Configuration cfg)
{
using (var file = File.Open(SERIALIZED_CFG, FileMode.Create))
{
var bf = new BinaryFormatter();
bf.Serialize(file, cfg);
}
}
/// /// 加載映射文件,先判斷映射文件是不是最新的
/// /// 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;
}
}
/// /// 判斷程序有沒(méi)有改動(dòng),如果有返回false,即再重新序列化(一個(gè)是判斷應(yīng)用程序,一個(gè)是判斷配置文件)
/// 如果沒(méi)有,則返回true,即加載以前序列化的文件
/// /// 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;
}
}
}
這個(gè)很適合我們要經(jīng)常啟動(dòng)NH應(yīng)該程序的環(huán)境中,比如開(kāi)發(fā)或測(cè)試的時(shí)候,也很適合基于WinForm的項(xiàng)目。但對(duì)于B/S就不那么適用了,因?yàn)橥鵅/S中應(yīng)用程序只啟動(dòng)一次。