Avoid using New Keyword with DbContext in EF and EF core
A lot of legacy apps didn’t use dependency injection in their apps. As a result, many of them have a lot of instantiations of their DbContext classes. Doing this has its own issues, not the least of which is the tight coupling it introduces. Let’s dive into our example to see the problem of instantiation DbContext.
The SaveChanges in UpdateProfile does nothing.The db instance in ProfileService isn’t tracking the entity, The name will remain unchanged. To make the above code work we can attach the entity first and then update it.
That’s a lot of work to try and get just right to get the expected behavior. The code’s brittle, full of duplication, and worse have non-obvious temporal dependencies.
So, For ASP.NET (Core) apps, you should be sure only to have a single instance of a DbContext per request, and the best way to achieve this is through the use of a DI container like Autofac (or the built-in ASP.NET Core (ServiceCollection
)
Don’t surprise consumers of your classes with hidden dependencies. If your class needs it, it should ask for it in its constructor. And if “it” couples the class to infrastructure, it should be asking for an abstraction (interface) not creating an instance directly using new and not calling a static method.
In .Net Framework, you can use Autofac.MVC5 nuget package. your global.asax and update Application_Start()
In .Net Core Startup.cs update ConfigureServices and add this code
If you need a lot of details you can read