4

I am planning on moving to EF for data access in an ASP.NET WebForms application. I would like to know when is the appropriate time in the ASP.NET page lifecycle to create my derived DbContext.

Should it be created on page initialization and the shared during the various page lifecycle events?

Should it be created during the specific page lifecycle event when data access is needed?

Should it be created on application request creation and shared through the HttpContent?

user1282345
  • 251
  • 3
  • 6

1 Answers1

1

This is not a specific answer, but DbContext is designed around a Unit of Work pattern. On a practical level, it is intended to be new’d up, used for a clearly defined (visible) set of operations, committed, and disposed.

I strongly recommend against attaching it to HttpContext or other items whose lifetime is not immediately obvious or in your control. You should always know what state it’s in, and it should not be subject to side-effects – such as other methods that operate on it out of sight. Keep it as short-lived as possible.

Matt Sherman
  • 8,298
  • 4
  • 37
  • 57