Reputation: 3384
Sorry if this is answered earlier, I would like to know what is the best way to handle connection in MVC 6 with EF Core 2.0. Should i use singleton instance (Servics.AddSingleton ) of DBContext or any better way to handle it. If there are multiple instances of DBContext, i will endup having my entities into disconnected state. How to handle that situation then ?
Upvotes: 0
Views: 503
Reputation: 239260
First, it's a bit of a pet-peeve, but there is no such thing as MVC 6. There's ASP.NET MVC and ASP.NET Core, where MVC is the older framework running on full .NET and Core is the newer framework that runs on .NET Core.
As @DavidG points out, you should never have a context in singleton-scope. Your context should always be in request-scope or what ASP.NET Core's DI container simply calls "Scoped". This will ensure that there's only one instance of your context per request, which is exactly what you want. The fact that other requests will have their own instance should not be an issue unless you're doing nasty non-thread-safe things that cross request-boundaries (which you should not do).
Finally, having detached entities isn't a problem in itself. You simply attach them when you need to do something atomic with them.
Upvotes: 2