Add NHibernate Configuration in web.config, and reuse an existing connectionstring
When we use nHibernate in asp.net, most time we use a nhibernate.cfg.xml to define the database connection. And for some scenarioes, we may also have a database connection defined in web.config. So, there might be 2 definitions for the same database. Here is the way to combine the 2 definitions and in web.config.
in web.config
1: <configuration>
2: <configSections>
3: <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
4: </configSections>
5: <appSettings>
6: </appSettings>
7: <connectionStrings>
8: <add name="MyDefaultDatabase" connectionString="Data Source=......" />
9: </connectionStrings>
10: <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
11: <session-factory>
12: <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
13: <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
14: <property name="connection.connection_string_name">MyDefaultDatabase</property>
15: <property name="command_timeout">300</property>
16: <property name="show_sql">false</property>
17: </session-factory>
18: </hibernate-configuration>
19: ……………
and pay attention,
- The secion name must be ‘hibernate-configuration’ , or it will not work. Very tricky.
- The type must be ‘NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" , also very tricky.
- Use connection.connection_string_name if you want to reuse an existing database connection.
- in your code, use
new NHibernate.Cfg.Configuration().Configure(); instead of given a nhibernate.cfg.xml file parameter.
Now, you only have 1 database connections in your web.config~

