DbContext在长期运行过程中的生命周期 [英] Life time of DbContext in a long-running process

查看:234
本文介绍了DbContext在长期运行过程中的生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个长期运行的进程(例如Windows服务),需要从多个线程访问数据库。

Say I have a long-running process (e.g. Windows service) which needs to access a database from multiple threads.

DbContext也不是线程安全的,也是一个好主意是不要长时间保留它(似乎在Web环境中公认的最佳实践是为每个请求创建一个新上下文)。

DbContext is not thread safe, also it is a good idea not to keep it around for a long time (seems that an accepted best practice in the web environment is to create a new context for each request).

基于在EF文档中,上下文应该是短命的并且被丢弃,因此已经实现为非常轻量级并且可以在可能的情况下重新使用元数据,因此似乎为每个数据库创建一个新的数据库上下文在这种情况下,可能要进行操作,但这似乎有点过分。

Based on EF docs, Contexts are expected to be short-lived and discarded, and as such have been implemented to be very lightweight and reutilize metadata whenever possible, so it seems like creating a new DB context for each database operation might be a way to go under these circumstances, but it does seem a bit excessive.

有想法吗?

推荐答案

当然可以短时间运行,但这不仅是由于数据库方面的考虑,还因为应用程序体系结构:如果您的体系结构是Clean Code(根据Bob Martin),则是网站或Windows服务对数据库一无所知,他们只需将应用服务创建为&在需要的时候。应用程序服务应负责控制数据库会话的生命周期以及它们从中获得的所有比特。对我来说真的很好。

Short-running, for sure, but not only because of DB considerations, also because of application architecture: if your architecture is Clean Code (as per Bob Martin), a Website or Windows Service would not know anything about the database, they would simply create an Application Service as & when required. The Application Service(s) should be responsible for controlling the lifecycle of the database session, and all the bits they get from it. Works really well for me.

这篇关于DbContext在长期运行过程中的生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆