How to load application settings to NHibernate.Cfg.Configuration object?

user366312 picture user366312 · Dec 31, 2009 · Viewed 28.3k times · Source

How to load application settings to NHibernate.Cfg.Configuration object by using System.Configuration.ConfigurationManager from App.config?

Answer

Lachlan Roche picture Lachlan Roche · Feb 18, 2010

The hibernate configuration can also be moved into app.config, which simplifies the startup code. See section XML Configuration File in the NHibernate reference manual.

Configuration cfg = new NHibernate.Cfg.Configuration();
ISessionFactory sf = cfg.Configure().BuildSessionFactory();

And in app.config:

<configuration>
        <configSections>
            <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
        </configSections>
        <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
            <session-factory>
                <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
                <property name="connection.dialect">NHibernate.Dialect.MsSql2005Dialect</property>
                <property name="connection.connection_string_name">Northwind</property>
                <property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
                <mapping assembly="assemblyname" />
            </session-factory>
        </hibernate-configuration>
        <connectionStrings>
                <add name="Northwind" connectionString="Data Source=(local);Initial Catalog=Northwind;Trusted_Connection=True;>
        </connectionStrings>
</configuration>