I recently refactored a WPF app so that it no longer wraps each use of the DbContext in a using clause (see this question). Instead, my app just uses the same DbContext singleton throughout.
This works great except for one small problem. I have a routine that rebuilds the database from scratch and inserts some default data. This routine uses ADO.NET directly (not the DbContext), so the DbContext is unaware that the database is now completely different.
Is there a method to reset the DbContext without disposing it? I’d like to avoid disposing if possible because this would break several references to the original singleton throughout the app.
I was not able to come up with a method to reset the global DbContext. I was able to solve my problem, however, by injecting a
DbContextLocatorinto any class that needs a DbContext instead of passing the DbContext itself.My goal was to maintain a global DbContext, but allow it to be reset whenever needed (such as after a database rebuild or import).
My solution uses an abstract base class and a concrete class.
Base Class
Concrete Class
Usage
Get the current DbContext:
Reset the DbContext:
Edit
Based on Shimmy’s feedback, I made
DbContextLocatorBaseinto a generic. (I’m also now implementingIDisposable.)Base Class
Concrete Class (optional, since the base class is no longer abstract)