0
votes

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

1 Answers

1
votes

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