tags:

views:

114

answers:

1

Hi all,

I'm currently creating a system which in some cases, if the database is not available, uses a MSMQ instead. E.g. if the application (in one of the cases it's a wcf web service) starts, and the database is not available, all incoming requests should be written to the MSMQ. When the database is available again, the requests should be written to the db again. I am using NHibernate and the session factory is wrapped by a singleton. This is what the service looks like:

try
{
   // to database (just an example)
   SessionProvider.Current.CurrentSession.Save...       
}
catch(NHibernate.ADOException)
{
   // to msmq
}

This setup works when the service is up and running for some time and the session factory has been build. When stopping the SQL server ADO exceptions are raised and things are written to the MSMQ properly.

Now my problem. If the database is not available BEFORE the service is started the first time, the session factory cannot be build and a TypeInitializationException is thrown. My singleton session provider is now broken. So when the database is running again, I somehow need a way to rebuild the session factory. Would I do that timer based? Like trying to rebuild it every 5 minutes? How can I 'reinstantiate' a singleton?

Here's an excerpt of the session provider pattern I am using:

public sealed class SessionProvider : ISessionProvider
{
    private ISessionFactory sessionFactory;

    private SessionProvider()
    {
     sessionFactory = new Configuration().Configure().BuildSessionFactory();
    }

    public static ISessionFactory SessionFactory
    {
        get 
        {
            return Nested.SessionProvider.sessionFactory;
        }
    }

    public static ISessionProvider Current
    {
        get 
        {
            // TypeInitializationException is thrown when building session factory fails
            return Nested.SessionProvider;                                
        }
    }

    private class Nested
    {
        internal static readonly SessionProvider SessionProvider = new SessionProvider();
    }
}
+1  A: 

I suggest you change your SessionProvider like this:

...     
       private ISessionFactory sessionFactory;
       private Configuration config;

            private SessionProvider()
            {
                config= new Configuration();
                config.Configure();
            }


        public static ISessionFactory SessionFactory
            {
                get 
                {
                    if(sessionFactory==null)
                       sessionFactory=config.BuildSessionFactory();

                        return Nested.SessionProvider.sessionFactory;
                }
            }
...
Beatles1692