Reputation: 2809
I implemented repository pattern to my software by the help of this article. One question boggles my mind. I think Database class should implement singleton pattern because user should not create more than one database context using "var ourDatabase = new Database();"
statement. Am i right or is this situation not a criticial issue for usage of the implementation.
Upvotes: 2
Views: 3519
Reputation: 7448
You should not have the database context as a singleton with Entity Framework. For starters, each context instance tracks all changes made to it and "save changes" saves all the changes. So, if you have a web application and you made your context a singleton then all the users would be updating the same context and when one called "save changes" it would save changes for everyone. In a single-user Windows application this is less of an issue, unless you have different parts of the application working in parallel.
Also be mindful that the context caches data it has already loaded and tracks changes by default. In short, this can mean memory bloat and decreased performance as more and more objects are tracked - though in practice the impact of this varies.
From a performance point of view, Entity Framework implements connection pooling underneath the covers so don't worry about creating and disposing database context objects - it is very cheap.
Upvotes: 7