Multiple SessionFactories in Windows Service with NHibernate

Posted by Rob Taylor on Stack Overflow See other posts from Stack Overflow or by Rob Taylor
Published on 2010-05-28T17:09:12Z Indexed on 2010/05/28 17:12 UTC
Read the original article Hit count: 286

Filed under:
|
|
|

Hi all,

I have a Webapp which connects to 2 DBs (one core, the other is a logging DB).

I must now create a Windows service which will use the same business logic/Data access DLLs. However when I try to reference 2 session factories in the Service App and call the factory.GetCurrentSession() method, I get the error message "No session bound to current context".

Does anyone have a suggestion about how this can be done?

public class StaticSessionManager
{
    public static readonly ISessionFactory SessionFactory;
    public static readonly ISessionFactory LoggingSessionFactory;

    static StaticSessionManager()
    {
         string fileName = System.Configuration.ConfigurationSettings.AppSettings["DefaultNHihbernateConfigFile"];
         string executingPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
         fileName = executingPath + "\\" + fileName;
         SessionFactory = cfg.Configure(fileName).BuildSessionFactory();

         cfg = new Configuration();
         fileName = System.Configuration.ConfigurationSettings.AppSettings["LoggingNHihbernateConfigFile"];
         fileName = executingPath + "\\" + fileName;
         LoggingSessionFactory = cfg.Configure(fileName).BuildSessionFactory();
    }
}  

The configuration file has the setting:

<property name="current_session_context_class">call</property>

The service sets up the factories:

private ISession _session = null;
private ISession _loggingSession = null;
private ISessionFactory _sessionFactory = StaticSessionManager.SessionFactory;
private ISessionFactory _loggingSessionFactory = StaticSessionManager.LoggingSessionFactory;

...

_sessionFactory = StaticSessionManager.SessionFactory;
_loggingSessionFactory = StaticSessionManager.LoggingSessionFactory;

_session = _sessionFactory.OpenSession();
NHibernate.Context.CurrentSessionContext.Bind(_session);
_loggingSession = _loggingSessionFactory.OpenSession();
NHibernate.Context.CurrentSessionContext.Bind(_loggingSession);

So finally, I try to call the correct factory by:

ISession session = StaticSessionManager.SessionFactory.GetCurrentSession();

Can anyone suggest a better way to handle this?
Thanks in advance!
Rob

© Stack Overflow or respective owner

Related posts about .NET

Related posts about nhibernate