0

I'm ASP.Net MVC trainee. and I use Entity Framework. but I'm Tense for create an instance from ApplicationDbContext in every controller class. And I think that will make a huge size in server memory, is what's happen is that the the asp move the database to memory? or just create an object with references?. is create a static object of ApplicationDbContext will make things better? And what's the ideal way to work with Entity Framwork?

LofiMAM
  • 127
  • 1
  • 11

1 Answers1

0

Repository + Dependency Injection can be a good practice.
You can use a generic repository and inject your DbContext into that for only once.

Amir Molaei
  • 3,700
  • 1
  • 17
  • 20
  • I'm so sorry, but I have no idea what are you talking about. – LofiMAM Feb 19 '19 at 09:10
  • When I work, I just use a basic asp `mvc` 5 approach, I just use `ApplicationDbContext` class with `LinQ` methods and `SaveShanges` method. – LofiMAM Feb 19 '19 at 09:16
  • To keep it simple, you can ignore Repository and just focus on Dependency Injection pattern. Ninject is a good tool to implement that. Just search for dependency injection and you will see plenty of resources to read. If it didn't help, feel free to ask for more details. – Amir Molaei Feb 19 '19 at 09:24
  • After studying dependency injection concept, you use these two links to impliment what you need: https://stackoverflow.com/questions/41347607/inject-entity-framework-dbcontext-using-ninject-in-asp-net-mvc5 https://stackoverflow.com/questions/16172448/how-to-inject-the-entity-framework-dbcontext-into-the-configurationbasedreposito/16174311 – Amir Molaei Feb 19 '19 at 09:31
  • Thank you so much. I will see and study them and back to you to complete with Repository. but I'm sorry form my urgency, I just would ask you again about how `ApplicationDbContext` object has been created and worked, if I have an 100 clients online on my website, is that means there are 100 hundred `ApplicationDbContext` objects in memory? and how I can observe the memory? and the most important question is how I can remove all objects and data that I don't need them after the view is sent to client? – LofiMAM Feb 19 '19 at 10:18
  • Entity Framework and Garbage Collector handle the connections and disposals for you and you don't need to worry about them. Here are some other links that may answer your concerns: https://blog.jongallant.com/2012/10/do-i-have-to-call-dispose-on-dbcontext/ https://softwareengineering.stackexchange.com/questions/359667/is-it-ok-to-create-an-entity-framework-datacontext-object-and-dispose-it-in-a-us https://stackoverflow.com/questions/15666824/entity-framework-and-context-dispose – Amir Molaei Feb 19 '19 at 10:47