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();
using (var stream = File.OpenWrite("Configuration.bin"))
    serializer.Serialize(stream, cfg);
using (var stream = File.OpenRead("Configuration.bin"))
    cfg = serializer.Deserialize(stream) as Configuration)


No Comments

Add a Comment

As it will appear on the website

Not displayed

Your website