Does ASP.NET multithreading impact Structuremap singleton class?

雨燕双飞 提交于 2019-12-05 20:02:41

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:

  • it is long running, opened and not closed among more requests - possible lock issues. Or
  • there is needed some open/close ISession management, not based on the current request

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.)

You must make the singleton thread-safe by making sure that every property set block uses a lock, like so:

public int Counter
{
    get { return _counter; }

    set
    {
        lock(_counterLock)
        {
            _counter = value;
        }
    }
}

private int _counter = 0;

private object _counterLock = new Object();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!