简体   繁体   English

结合单例模式和存储库模式

[英]Combining singleton pattern and repository pattern

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();" 我认为Database类应该实现单例模式,因为用户不应使用"var ourDatabase = new Database();"创建多个数据库上下文"var ourDatabase = new Database();" statement. 声明。 Am i right or is this situation not a criticial issue for usage of the implementation. 我是对的还是这种情况不是使用实现的批评性问题。

You should not have the database context as a singleton with Entity Framework. 您不应该将数据库上下文与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. 因此,如果您有一个Web应用程序,并且将上下文设为单例,则所有用户都将更新同一上下文,并且当一个名为“保存更改”的上下文将为所有人保存更改。 In a single-user Windows application this is less of an issue, unless you have different parts of the application working in parallel. 在单用户Windows应用程序中,这不是问题,除非您具有应用程序的不同部分并行工作。

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. 从性能的角度来看,Entity Framework在幕后实现了连接池,因此不必担心创建和处理数据库上下文对象-它非常便宜。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM