A colleague and I were just talking about unit testing when I realised that I write code differently in certain circumstances...
If I'm using Entity Frameworks on its own, I'll tend to use the IDisposable
interface via a using
block:
using (Context ctx = new Context()) { whatever(); }
But when I'm writing code that will be unit tested, I move the instantiation of the context into a constructor, so that I can pass in mocks to be used instead. I understand that this is a type of dependency injection, specifically "constructor injection".
Taking only a cursory look, I see this latter pattern recommended in a couple of articles:
- Mocking Entity Framework when Unit Testing ASP.NET Web API 2
- Entity Framework Testing with a Mocking Framework (EF6 onwards)
The problem with this (as my colleague and I reflected) is that the dispose method is never called. I suppose these objects get finalised as they move out of scope, but it seems less than ideal.
So, my question: is there a way to combine dependency injection with use of IDisposable?
I can imagine three possible categories of answer:
- "Yes, there is a way and here's how..."
- "No, there isn't a way. This is something you'll have to live with."
- "Tom, you have completely misunderstood something."
Whichever it is, we'd be really grateful!