Does ASP.NET multithreading impact Structuremap singleton class?

你离开我真会死。 提交于 2020-01-13 16:25:12

问题


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;
   }
}

回答1:


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




回答2:


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();


来源:https://stackoverflow.com/questions/16919579/does-asp-net-multithreading-impact-structuremap-singleton-class

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