Home > .Net, NHibernate > NHibernate configuration, set database connection credentials

NHibernate configuration, set database connection credentials

NHibernate configuration, set database connection credentials

Our team started to use NHibernate ORM, it used in part of the components of our Application (Mostly stand alone services).
There are interesting issues bloomed up:
How to use the same DB credentials while you are using NHibernate and standard ADO approach to retrieve, save and update your data. We have plenty Legacy code that cannot move to use NHibernate configuration file. Our main application used standard sql connection string from App.Config file, of cause we doesn’t want to maintain two configuration files.

“hibernate.cfg.xml” file contains basic configuration settings, used by NHibernate; for more detail see … [web site] User Id=;Password=;Data Source=;Pooling=false


We have created following Interface that will retrieve DB credentials from our application main configuration and set to NHibernate configuration object, such manner of development give us ability to keep backward compatibility.

///

/// Used to pass Database credentials to NHibernate

///

public interface IDBCredentials

{

    string DBUserName { get; set; }

    string DBPassword { get; set; }

    string DBDataSource { get; set; }

}

 

Following method initiates NHibernate configuration that partly will be retrieved from hibernate.cfg.xml and connection string from our main configuration file (App.Config) replaced by ours custom DB credentials object that was filled before.
m_sessionFactory data member is responsible for Session object creation (with updated configuration file).

private void InitSessionFactory()

{

    NHibernate.Cfg.Configuration configuration = new NHibernate.Cfg.Configuration().Configure();

 

    if (DBCredentials != null)

    {

    configuration.SetProperty("connection.connection_string", string.Format("User Id={0};Password={1};Data Source={2};Pooling=false"

    , DBCredentials.DBUserName

    , DBCredentials.DBPassword

    , DBCredentials.DBDataSource

    ));

    }

 

    m_sessionFactory = configuration.BuildSessionFactory();

}

This was an easy and elegant solution that has facilitated our deployment.

Categories: .Net, NHibernate Tags: ,
  1. No comments yet.
  1. No trackbacks yet.