When to instantiate DbContext in WebForms page lifecycle?

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

Should it be created when the page is initialized and shared during various page lifecycle events?

Should it be created during a particular page lifecycle when data access is needed?

Should it be created when the app request is made and passed through HttpContent?


source to share

1 answer

This is not a specific answer, but the DbContext is designed around the Unit of Work pattern. On a practical level, it is intended for beginners using a well-defined (visible) set of operations, execution and placement.

I highly recommend not attaching it to HttpContext or other items whose life is not immediately obvious or controlled by you. You should always know what his condition is and he should not be subject to side effects - for example, other methods that act on him out of sight. Keep it as short as possible.



All Articles