✅ EF Core, Proper DbContext Instantiation
When instantiating the DbContext, I've always created it in a Repository class (not a generic repository, rather a unit of work repository). First I extend the DbContext to allow construction via connection string, like so.
Then in the Repository class, I instantiate it like so:
This works fine for me, but I've seen a lot of examples where the DbContext is injected in the front-end. Hence, it is never instantiated. My question is, what are the reasons for this? Is it really advantageous to inject the DbContext? Is the way I do it an absolute no-no?
2 Replies
Just use DI
One, it's easier because you don't need to do the disposing yourself
Two, you leave the decision on when to spawn a new context and when to dispose of it to the framework
And believe me, the framework knows best when to do those things
Thanks for your input 🙂