A simple little class I whipped up. It's just a ConnectionProvider that uses the NHibernate hibernate.connection.connection_string setting to look up a corresponding connection string in the web.config or app.config.
Feel free to change the namespace, of course :)
Code:
using System;
using System.Collections.Generic;
using System.Text;
using NHibernate.Connection;
using System.Data.OracleClient;
using System.Configuration;
using System.Web.Configuration;
using System.Data;
using NHibernate.Util;
using NHibernate;
namespace Stanford.Slac.NHibernateUtil.Connection
{
/// <summary>
/// Provides connections to NHibernate from connection strings stored
/// in the standard ASP.NET 2.0 web.config "connectionStrings" section.
/// </summary>
public class ConnectionStringsSectionConnectionProvider : ConnectionProvider
{
/// <summary>
/// Gets an IDbConnection based on the connection name set in
/// the hibernate.connection.connection_string setting of your nHibernate config.
/// </summary>
/// <returns>An IDbConnection of the type defined by the NHibernate dialect.</returns>
/// <remarks>
/// NOTE: The type of the IDbConnection is determined by the NHibernate
/// hibernate.dialect setting, *not* the "providerName" attribute on the "add" element
/// in the "connectionStrings" section of the config.
/// </remarks>
/// <seealso cref="System.Configuration.ConnectionStringSettings">System.Configuration.ConnectionStringSettings</seealso>
public override System.Data.IDbConnection GetConnection()
{
ConnectionStringSettings settings = null;
if (null != System.Web.HttpContext.Current)
{
settings = WebConfigurationManager.ConnectionStrings[this.ConnectionString];
}
if (null == settings)
{
settings = ConfigurationManager.ConnectionStrings[this.ConnectionString];
}
if (null == settings || String.IsNullOrEmpty(settings.ConnectionString))
{
throw new HibernateException("Could not configure NHibernate.",
new ArgumentException("hibernate.connection.connection_string",
"'" + this.ConnectionString + "' did not correspond to any defined connections in " +
"the connectionStrings section of the config file."));
}
IDbConnection conn = this.Driver.CreateConnection();
conn.ConnectionString = settings.ConnectionString;
conn.Open();
return conn;
}
}
}