views:

534

answers:

4

Hi, Shouldn't classes in DAL (customerDAL) be singleton? Since my controllers (customerController) exposes "Shared Subs", then on every call, there is no need to create a new DAL object if already existed. Correct?

Thanks

+3  A: 

If you have a web site singleton dal objects are very dangerous because every request to the site is part of the same application. If you build them wrong, they can become bottlenecks for access to the database.

Joel Coehoorn
Yeah, except that, other than in rare exceptions, the DAL contains no state and this won't be a problem at all, since there is nothing to lock() or anything like that.
Robert C. Barth
+3  A: 

It highly depends on the architecture of your complete solution. One singleton may play hard to get when you have many consumers. Here is a checklist of things you may want to consider when designing DAL. Also, there are lots of DAL patterns like Repository and some facade like patterns.

Perpetualcoder
where can I see some dal patterns?
Saif Khan
I do not know of any one stop resource for this but if you google around you will find them for sure. Perhaps you could edit your question and add this bit. It will help both of us :)
Perpetualcoder
+2  A: 

Singleton objects are notoriously hard to test. I would look at creating your DAL in such a way that it isn't expensive to instantiate and then creating a new one as needed. This way you'll be able to write unit tests for DAL much more easily and still not incur much overhead. Additionally, if you create the DAL as a singleton, you'll need to be much more concerned with making it thread-safe if you use it in a multi-threaded environment (such as a web app).

tvanfosson
A: 

Singleton should only be used when you want to make sure only one instance of a class is ever instantiated inside an instance of your application.

Singleton could barely be considered a Code Smell. Most of the people who use Singleton uses it badly. Therefor, when you see one there is a great chance that it's not used properly.

As for the DAL, objects are not expansive to create. They should rely on using a connection pool and then request a connection from the pool every time a command need to be executed.

Of course, there is different patterns available and you should mostly use an ORM unless the request needs to be tweaked for performance.

See NHibernate, SubSonic, Linq2Sql, Entity Framework (yet to be released?), etc.

Maxim