下面是我在网上看到的一段代码,是关于单例模式的:public sealed class Singleton
{
Singleton()
{
InitSessionFactory();
} private void InitSessionFactory()
{
//connection to DB...
} public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to type as beforefieldinit
static Nested()
{
} internal static readonly Singleton instance = new Singleton();
} public ISession GetSession()
{
return sessionFactory.OpenSession();
} private ISessionFactory sessionFactory;
}
在使用的时候我发现,如果GetSession()时发现异常(如网络断线),则由于延迟加载的缘故,之后再调用GetSession()返回的都是异常,它不能自动恢复。所以我想在某个地方加入判断语句,如果出现异常就重新执行InitSessionFactory()重新连接数据库。
{
Singleton()
{
InitSessionFactory();
} private void InitSessionFactory()
{
//connection to DB...
} public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to type as beforefieldinit
static Nested()
{
} internal static readonly Singleton instance = new Singleton();
} public ISession GetSession()
{
return sessionFactory.OpenSession();
} private ISessionFactory sessionFactory;
}
在使用的时候我发现,如果GetSession()时发现异常(如网络断线),则由于延迟加载的缘故,之后再调用GetSession()返回的都是异常,它不能自动恢复。所以我想在某个地方加入判断语句,如果出现异常就重新执行InitSessionFactory()重新连接数据库。
{
try{
return sessionFactory.OpenSession();
}
catrch
{
做事。。
}
}
现在主要的问题在于instance是一个静态的只读的属性,GetSession()也只是它的一个方法,如果instance是异常的,那么GetSession()返回的也还是异常。所以是不是应该想办法让instance恢复正常呢?