In my ASP.NET MVC project I have a class which is instantiated via Structuremap and is configured as a singleton.
Given that ASP.NET is inherently multithreaded and the Singleton pattern is not threadsafe by default, will it cause any issues?
I faced an issue where multiple instances were being returned for a class configured as Singleton. Could this problem be because of the instances being requested from different threads.
EDIT : A more detailed description is given on this question.Structuremap in Singleton returning multiple instances
EDIT2 : Here is a description of what my class does
class DerviedClass: BaseInterface
{
ISession session
DerivedClass()
{
session = ObjectFactory.GetInstance<ISession>();
}
public bool DoWork
{
return session.QueryOver<MyTable>().RowCount() > 0;
}
}
You must make the singleton thread-safe by making sure that every property set block uses a lock, like so:
Taking into account your extended version, the example of the
DerviedClass
: I would say, that this is a very risky, and could cause lot of issues.My concerns:
1) ASP.
NET
+NHibernate
==ISession
per Request. Other words, when application starts (triggered by first request most likely, which could be more often if automated restarts ar in place), the Singleton is created and provided with an instance of theISession
per Current Request i.e First Request.Well at least, the
ISession
should be recieved viaFactory
whenever needed, to be sure, that it is Current Request related.2) In case, that the NHibernate
ISession
created in constructor, is intended to be indpendent on the Current Request, it could mean:The point is, that I do not see the benefit of the Singleton pattern here. We do not need and do not provide common, request indpendent stuff.
We do return data dependent to the request (and its session scope). So, what I would suggest to use:
The overhead with creating instance per request is nothing in comparison with the benefit of logical life-cycle usage.
But, yes, this is just my suggestion... Because I see many potential issues (locking, un-intended changes ala dirty object in the session which could be commited etc.)