Lesser-Known NHibernate Features: Serializing Configuration

This isn’t exactly a feature of NHibernate, but it is something that you can do with it and most people isn’t aware of.

If you have a big number of classes and mappings in your domain, adding all of them to a Configuration instance can take some time.

NHibernate allows you to serialize the Configuration instance with all the mappings that it contains so that you can deserialize it later, which can result in reduced startup time. The disadvantage is that if you change any of the mappings, you have to discard the serialized file and build a new one.

Here’s how you can do it:

var serializer = new BinaryFormatter();

 

//serialize

using (var stream = File.OpenWrite("Configuration.bin"))

{

    serializer.Serialize(stream, cfg);

}

 

//deserialize

using (var stream = File.OpenRead("Configuration.bin"))

{

    cfg = serializer.Deserialize(stream) as Configuration)

}

Published by

Ricardo Peres

Team Leader at Dixons Carphone. Microsoft MVP.

Leave a Reply

Your email address will not be published. Required fields are marked *