I used to implement my repository classes as you can see below
public Class MyRepository
{
private MyDbContext _context;
public MyRepository(My
The root rule is : your DbContext lifetime should be limited to the transaction you are running.
Here, "transaction" may refer to a read-only query or a write query. And as you may already know, a transaction should be as short as possible.
That said, I would say that you should favor the "using" way in most cases and not use a private member.
The only one case I can see to use a private member is for a CQRS pattern (CQRS : A Cross Examination Of How It Works).
By the way, the Diego Vega response in the Jon Gallant's post also gives some wise advice :
There are two main reasons our sample code tends to always use “using” or dispose the context in some other way:
The default automatic open/close behavior is relatively easy to override: you can assume control of when the connection is opened and closed by manually opening the connection. Once you start doing this in some part of your code, then forgetting to dipose the context becomes harmful, because you might be leaking open connections.
DbContext implements IDiposable following the recommended pattern, which includes exposing a virtual protected Dispose method that derived types can override if for example the need to aggregate other unmanaged resources into the lifetime of the context.
HTH