0

I'm implementing a DAL using the Entity Framework. We have some DAL classes (I call them repositories) instantiating or receiving a context by parameter every time a method is called. I don't like that kind of behavior; I'm not documented about this issue but my common sense says me that context's instantiation consumes too much system resources. So:

  1. Is context's instantiation expensive?
  2. If you've answered "yes" to 1, how would you tackle this problem from a design viewpoint?
  3. If you've answered "yes" to 1, how would you implement the solution in C#?
  4. Which approach do you recommend to implement a DAL for a web application?
JPCF
  • 2,232
  • 5
  • 28
  • 50

2 Answers2

3

my common sense says me that context's instantiation consumes too much system resources

Common sense is nearly useless when it comes to optimization.

What exactly in the constructor of context do you suppose will be problematic? Have you read the source for it yet?

1) Is context's instantiation expensive?

Relative to what? Compared to the amount of time required to establish a database connection? Compared to the time it takes to perform your site's DNS lookup? Compared to the amount of time a browser might spend rendering your page?

The vast liklihood is that context's instantiation is not particularly time consuming compared to the time required to actually retrieve data across the network.

2) If you've answered "yes" to 1, how would you tackle this problem from a design viewpoint?

Use a UnitOfWork abstraction. Each UnitOfWork should contain a single entity context. If this is a web app you should have one UnitOfWork per request.

Community
  • 1
  • 1
quentin-starin
  • 26,121
  • 7
  • 68
  • 86
1

Context lifetime management is a crucial when using ORMs. The entity framework context in keeps information about loaded entities for lazy loading and change tracking purposes and its memory footprint may grow very quickly. If you don't dispose your context you will essentially have a memory leak.

However, you are correct that keeping the context lifetime too short is not ideal since you would probably like to make use of change tracking.

using (var context = new DataContext())
{
    context.Products.Add(product);
    context.SaveChanges();
}

The above example shows disposes the context too quickly to take advantage of the change tracking goodies.

For Web applications you should use context per request.

For Win Form applications you can dispose of your context when you move from one form to another.

Jeremy Seekamp
  • 2,746
  • 1
  • 22
  • 25