Wednesday, September 8, 2010

Fluent NHibernate Spring.NET Session Factory

Fluent NHibernate requires a Spring.NET session factory other than the usual LocalSessionFactoryObject. The following implementation makes a few assumptions:

  1. We’re using MS SQL Server 2008
  2. All configuration files are fluent
  3. Connection string information will be available in the connectionStrings section of the configuration file (web.config or app.config).

Obviously you could adjust or generalize these, but this is sufficient for me now.

using System;
using System.Configuration;
using System.Reflection;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using Spring.Data.NHibernate;

namespace jsj.Spring.NHibernate
{
public class FluentNHibernateLocalSessionFactoryObject
: LocalSessionFactoryObject
{
public string[] FluentNhibernateMappingAssemblies { get; set; }

public string ConnectionStringName { get; set; }

protected override void PostProcessConfiguration(
global::NHibernate.Cfg.Configuration config )
{
base.PostProcessConfiguration( config );

FluentConfiguration fluentConfig = Fluently.Configure( config )
.Database( MsSqlConfiguration.MsSql2008.ConnectionString(
c => c.FromConnectionStringWithKey(
ConnectionStringName ) ) );

Array.ForEach( FluentNhibernateMappingAssemblies,
assembly => fluentConfig.Mappings(
m =>
m.FluentMappings.AddFromAssembly(
Assembly.Load(assembly))) );

fluentConfig.BuildSessionFactory();
}
}
}








It can be configured along the lines of







<object id="NHibernateSessionFactory" 
type
="jsj.Spring.NHibernate.FluentNHibernateLocalSessionFactoryObject, jsj.Spring">
<property name="DbProvider" ref="DbProvider"/>
<property name="ConnectionStringName" value="LocalSqlServer"/>
<property name="ExposeTransactionAwareSessionFactory" value="true" />
<property name="FluentNhibernateMappingAssemblies">
<list>
<value>jsj.Data</value>
</list>
</property>
<property name="HibernateProperties">
<dictionary>
<entry key="connection.provider"
value
="NHibernate.Connection.DriverConnectionProvider"/>
<entry key="dialect" value="NHibernate.Dialect.MsSql2008Dialect"/>
<entry key="connection.driver_class" value="NHibernate.Driver.SqlClientDriver"/>
<entry key="cache.use_second_level_cache" value="true" />
<entry key="cache.provider_class"
value
="NHibernate.Cache.HashtableCacheProvider,NHibernate" />
<entry key="max_fetch_depth" value="0" />
</dictionary>
</property>
</object>










and it will use the connection string identified as LocalSqlServer from the configuration file.