Search code examples
.netwebpetapocoobject-lifetime

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


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

  • handling requests in separate threads from a pool
  • requests are quick: no long polling, streaming, etc
  • but not necessarily ASP.NET, it may be for example Nancy

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

  • globally static (I guess no, due to this answer)
  • per-thread static, [ThreadStatic]
  • per-request
  • unit of work style: create and dispose as soon as the task is finished

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


Solution

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