amartynov
amartynov

Reputation: 4175

What is recommended lifetime of Database object in a web application?

I consider using PetaPoco in a conventional web app. Saying conventional I mean

What should be the lifetime of the Database object, and that of the underlying DbConnection?

I especially appreciate answers from those who run production apps with PetaPoco.

Upvotes: 0

Views: 271

Answers (3)

Eduardo Molteni
Eduardo Molteni

Reputation: 39413

Per request is the way to go

  • globally static: you guess right. Will bring problems accessing the same recordset and others. Definitely no.
  • per-thread static. You should avoid [ThreadStatic] in Asp.net
  • per-request: works great
  • unit of work style: It works great also (not my preference)

Upvotes: 2

Todd Menier
Todd Menier

Reputation: 39299

Database is a cheap object to create, so I just create it as needed. I use PetaPoco (or more specifically AsyncPoco so I'm not tying up threads during I/O bound work) in a busy web app and this works great for me. Others do prefer per-request though, and that should also work well.

Upvotes: 1

Guffa
Guffa

Reputation: 700242

You need one object per thread, but you shouldn't associate the object with the thread itself, because handling a request can start in one thread and finish in another thread.

Using one object per request would normally be the best, at least for quick request handling. However that is not always simple. If you risk leaving objects without disposing them (for example if there is an exception), it's better to use one object for a limited task where you can make sure that it is disposed properly.

Upvotes: 1

Related Questions