c# entity framework: correct use of DBContext class inside your repository class

前端 未结 10 1623
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 10:59

I used to implement my repository classes as you can see below

public Class MyRepository
{
      private MyDbContext _context; 

      public MyRepository(My         


        
10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-02 11:32

    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:

    1. 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.

    2. 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

提交回复
热议问题