开发者

Singleton - is it useful

开发者 https://www.devze.com 2023-02-23 08:46 出处:网络
If I have an object which works as a repository with Save(), GetPro开发者_如何转开发duct(prod id) etc, is it a good idea for this to be a singleton in an asp.net applications.

If I have an object which works as a repository with Save(), GetPro开发者_如何转开发duct(prod id) etc, is it a good idea for this to be a singleton in an asp.net applications.

My thought is that because I have many accesses to the database, this would improve performance because it doesn't waist time recreating the repository object each time. I haven't seen anything like this in any samples, so why is this wrong? Thanks


Just be carreful that a singleton in ASP .net means that all users of your web site will use it to access data. That means that you will probably have to lock you methods and that could results in bottlenecks.

I remember that one time I had a real strange bug with singleton data manager in an ASP app. If you don't want to recreate your repo each time a user request a page, you can also put you data repository object in the user session.


Unfortunately it really depends on how you access your Database, and how your repository class is really abstracting database connections, and transactions.

If you're just talking about the expenses of creating an in memory object for every http request then it's not a big deal. It's really not worth consideration.

If you're talking about low level database stuff, then again, it depends.

Particularly with ORMs like Linq to SQL or NHibernate, how you manage their sessions is quite important. Usually though you wouldn't want a "session's" or "datacontext's" scope to go beyond the http request, so no, a singleton wouldn't be a good idea IF the singleton is holding the DB Session as a singleton itself.

Consider using an IoC Container also, like Castle Windsor. Then to change a particular classe's "lifestyle" (singleton, transient, per web request, etc.) is a simple configuration change, and makes your application a bit more flexible.

Also, talking to the DB itself is more expensive that creating new objects in memory, so if you're really after performance consider clever caching.

Lastly, when considering Singletons, think about it from a conceptual point of view instead of performance. Does it make sense that this object be Singleton?

0

精彩评论

暂无评论...
验证码 换一张
取 消