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;
}
}
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 the ISession per Current Request i.e First Request.
Well at least, the ISession should be recieved via Factory 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:
.HybridHttpOrThreadLocalScoped()
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With