NHibernate X-Factories allow you to combine multiple .cfg.xml into one. X-Factories does this by allowing each session-factory to be named and referred to individually by name. This gives a cleaner and less verbose configuration for using NHiberate between multiple databases.
Setup is really quite simple.
- Install via NuGet.
- The
nhibernate-configuration-x-factories.xsd
scheme may be included to a Project or Solution and is available in the NuGet package root folder. - Change the
xmlns
attribute of thehibernate-configuration
element in your .cfg.xml tourn:nhibernate-configuration-2.2-x-factories
. - Change
hibernate-configuration
element tohibernate-configuration-x-factories
. - Give the
session-factory
element a name and create as manysession-factory
elements as you like.
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration-x-factories xmlns="urn:nhibernate-configuration-2.2-x-factories">
<session-factory name="Development">
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">
Server=dsql01;DataBase=dbDev;uid=nhDeveloper;pwd=pass1234
</property>
<property name="show_sql">true</property>
<mapping assembly="DataLayer" />
</session-factory>
<session-factory name="Production">
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">
Server=psql02;DataBase=dbDev;uid=nhDeveloper;pwd=pass5678
</property>
<property name="show_sql">false</property>
<mapping assembly="DataLayer" />
</session-factory>
</hibernate-configuration-x-factories>
using NHibernate;
using NHibernate.Cfg;
using NHibernate.XFactories;
NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
config
.Configure(HostingEnvironment.MapPath("~/nhibernate.cfg.xml"), "Development")
.BuildSessionFactory();
Required
- NHibernate ≥ 5.1.0 (http://nhforge.org/Default.aspx)
Optional
Licensed under the MIT.