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?

2 Answers
2

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", you should inject the context but the argument is different. You inject the context to be able to control its lifetime more precisely. For example, you could have a container controlled lifetime (a singleton) or a context which lasts for a lifetime of a request processing. As for mocking, you can mock your repository just by providing another implementation (or even using a mock library) of the repository interface; injecting the context has nothing to do about mocking.
–
Wiktor ZychlaAug 30 '12 at 21:02

In theory, this is a good idea, because you might need to change out your data store someday. In practice, this hardly ever happens, and mocking the data store produces tests whose sole purpose is to examine the API of your repository, an exercise that is not especially meaningful if your repository is just a thin veneer over a DAL.
–
Robert Harvey♦Aug 30 '12 at 21:03

@Robert: true. While this is common to mock the repository, I barely imagine mocking the data store just to test the repository itself. The dependency between the implementation of the repository and the underlying data store is stable. It is the dependency between the repository and its client which is volatile.
–
Wiktor ZychlaAug 30 '12 at 21:29

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.