0

It is a good idea to create a class that holds both the query and the context constructors as Func of Context and Func of IQueryable of TEntity for solving the context lifetime problem?

Example: On your data layer, if you use one context per method using the "using" statement, you can't return IQueryables because this wouldn't be valid after the context has been released, this makes you use of:

  • One context per form (This would need injecting the form context onto your data layer)
  • Thread static context
  • Call ToList() before returning the query (Disable query composition)
Rafael
  • 2,642
  • 2
  • 24
  • 30

1 Answers1

1

As far as I recall, contexts are designed to be created and recreated as needed, not statically kept in memory (though I have done it that way as well). I find it is usually perfectly fine to create a context in my class (like the controller class, or even view model class, of an MVC app), then have all methods use that.

However, if you have a LARGE amount of static data you want to cache for ALL users, I have kept that statically in memory. You'd just have to consider the threading, as you mentioned. If you are reading only, you can create read-only locks to access this data (not C# lock{}).

For more details if going static: https://msdn.microsoft.com/en-us/library/system.threading.readerwriterlock(v=vs.110).aspx

you don't really need to dispose of them in most cases - and that's by design https://stackoverflow.com/a/389871/1236397

Community
  • 1
  • 1
James Wilkins
  • 6,836
  • 3
  • 48
  • 73
  • The problem with having a context per ViewModel is that you should make your ViewModel IDisposable, because it has a reference to an IDisposable now (wich is the context), and that would make you have to dispose your view models properly (too complicated). I'm not saying that your query object should have a reference to the context, but to a delegate that returns a context, and internaly use that delegate (Func) to create short-lived contexts only when needed – Rafael Apr 23 '15 at 02:11
  • Why not let the GC handle it? I've never had to implement `IDisposable` ever for a view model using this method, and I never had any issues. – James Wilkins Apr 23 '15 at 02:12
  • Frankly I have not had problems with leaving alive the context before , but I've read in several places, before asking this question, different mechanisms to create and release the context and about the pollution of its entity cache, so I'm looking for a way to create it and dispose it properly. – Rafael Apr 23 '15 at 02:18
  • 1
    I didn't saw your edit, that's the answer. Thanks :) – Rafael Apr 23 '15 at 02:21