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:
- Is context’s instantiation expensive?
- If you’ve answered “yes” to 1, how would you tackle this problem from a design viewpoint?
- If you’ve answered “yes” to 1, how would you implement the solution in C#?
- Which approach do you recommend to implement a DAL for a web application?
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?
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.
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.