Sam
Sam

Reputation: 15770

Managing multiple NHibernate Sessions/UnitOfWork

I am fairly new to NHibernate, and I am trying to come up with a good pattern for using the Unit of Work pattern with NHibernate Sessions, but allowing for different Connection Strings to be used to connect to different databases/as different users.

I am leaning towards a Factory Pattern, because I need this to work with Oracle and SQL Server.

I am using Fluent NHibernate.

Any suggestions?

Upvotes: 1

Views: 283

Answers (1)

jbl
jbl

Reputation: 15413

You will need a different ISessionFactory, from a different configuration, for each of your connection strings.

Here is a very rough implementation for an ISessionFactory Factory. Note that configurations may differ in many ways (for example in DLL scopes), not only connection strings. So you may soon need to pass a whole configSection to your _buildConfiguration, or have _buildConfiguration implemented by a custom IMyConfigurationBuilder.

// The main method to be called with "oracle" or "sqlserver" as parameter
public NHibernate.ISessionFactory BuildSessionFactory(string configName)
{
    return GetConfiguration(configName).BuildSessionFactory();
}

public NHibernate.Cfg.Configuration GetConfiguration(string configName)
{
    switch (configName)
    {
        case "oracle": return _buildConfiguration("connectionstringtoOracleFromApplicationConfig");
        case "sqlserver": return _buildConfiguration("connectionstringtoSqlserverFromApplicationConfig");
    }
    return null;
}

private NHibernate.Cfg.Configuration _buildConfiguration(string connectionString)
{
    var cfg = new Configuration();
    //.
    //.
    cfg.Properties.Add("connection.connection_string", connectionString);
    //.
    //.
    return cfg;
}

Hope this will help

Upvotes: 1

Related Questions