-1

I create a service that reads from a single table through EF dbContext.

  • The dbContext is created in this service based on given connection string
  • The dbContext is private
  • The service exclusively reads from this table and never writes to it
  • No other contexts use this table, altough they use other tables in the same database
  • This table doesn't consist any foreign keys

Question: Having in mind all above should I dispose the context in this service by using a using statement? If yes, why?

I don't want to have to do it because it complicates tests extensively, but if I have to then by all means I'll do it.

Yoda
  • 17,363
  • 67
  • 204
  • 344
  • 1
    `I don't want to have to do it because it complicates tests extensively` Can you show us an example of such a test, just to confirm there isn't a way to do it in a way that doesn't complicate the tests extensively? – mjwills Mar 19 '18 at 09:53
  • 1
    I'd argue, that using EF for reading a single table is a bit of overkill. – Marco Mar 19 '18 at 09:53
  • 1
    If you are always reading with `AsNoTracking()` and also never use it from multiple threads - you should probably be fine in this case. – Evk Mar 19 '18 at 09:54
  • Just a thought, but if that is a strict readonly access, why use EF at all? I usually just use Dapper to SELECT the data in such a use case. –  Mar 19 '18 at 09:54
  • [Do I always have to call Dispose() on my DbContext objects? Nope](https://blog.jongallant.com/2012/10/do-i-have-to-call-dispose-on-dbcontext/) – Ivan Stoev Mar 19 '18 at 10:10

1 Answers1

3

Always initialize a context as late as possible and dispose it as soon as possible. If you don't do this, the context will keep growing and might start behaving like a memory leak, eventually giving you memory issues.

To do this, use using statement; or if you use a DI framework, use a lifetime that ends after each web request or something similar.

Also see: Memory leak when using Entity Framework

"It makes tests more complicated" is absolutely no reason for not following best practices. Not sure what you mean with that, either.

L-Four
  • 13,345
  • 9
  • 65
  • 109
  • You can add, that DataContext instantiation is a cheap operation. If it uses connection pool, no new connection will be established – Evgeny Gorbovoy Mar 19 '18 at 10:04