Should I be injecting my context into my repository classes?
-
29-06-2021 - |
题
I have many repository classes that look like the following:
public class ProfileRepository : IProfileRepository{
private MyEntities myEnt = new MyEntites();
...
}
the MyEntities
class are my entities that were generated in my .edmx file using Entity Framework. I constantly use this object in all my repository classes, and all my repository classes are injected into my controllers. Is there a way/is it good practice to inject the myEnt
object into my repository classes and will it work the same way with concurrency also?
解决方案
MyEntities
is your context, I'm assuming. If so, then yes, this is a good practice to inject your context into your repository. This way, you can mock your repository and then your unit tests can test functionality without having to worry about database (or other persistence store) connectivity.
其他提示
The answer is "yes".
The rationale is as follows: by creating the context instance in your repository you are NOT allowing the caller to control the lifetime of the context.
For example, in web-based scenarios, you don't want your context to be recreated with each creation of an instance of the repository class. Rather you want the context to live as long as the processing of a request lasts on the server.