I have an entity in EF called Registry that I use for throwing all kinds of useful stuff in. My typical query looks like this:
db.Registry
.Where(x => x.Domain == "SomeDomain" && x.Key == "SomeKey")
.Select(x => x.Value)
.Single();
where db is a variable of type EFContainer. Rather than having this sort of query all over the place I’d like to write something much simpler, perhaps like:
Registry.Get(Key: "SomeKey", Domain: "SomeDomain")
but the problem is that in order for that method to access the database it needs to instantiate EFContainer and when it does, I start to have errors that IEntity change tracker cannot handle the second connection. I suppose I could pass in my db variable to the method but that’s eeky.
What’s a good way to accomplish this?
The typical way to do this would be to create a RegisterRepository and inject either the EFContainer into the constructor of the repository or inject a mechanism for creating containers.
In this implementation you have to consider how you will obtain a reference to the repository and thus how the repository will be constructed. You may use a dependency injection framework to register the EF container and the repository with a proper lifetime scope. If for example you are developing an ASP.NET application, an EF context would be scoped by an HTTP request as would the repository.