Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# .Net核心上下文服务生命周期类型_C#_Asp.net Core - Fatal编程技术网

C# .Net核心上下文服务生命周期类型

C# .Net核心上下文服务生命周期类型,c#,asp.net-core,C#,Asp.net Core,我需要了解在.NETCore中为DBContext使用不同类型的生存期的利弊 我目前有一个问题,如果我打了多个电话,我会返回一个错误: InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of D

我需要了解在.NETCore中为DBContext使用不同类型的生存期的利弊

我目前有一个问题,如果我打了多个电话,我会返回一个错误:

InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext.
我知道我可以使用Transient ServiceLifeTime来解决这个问题,但有什么不好的地方,我应该怎么做呢?如果这个问题太抽象,请相应修改

编辑:

事实证明,通过构造函数注入作用域服务,它强制服务成为单例:


有人能告诉我如何使用Invoke或InvokeAsync吗?我不知道如何不使用构造函数。

您的应用程序将为每个客户端请求创建一个新的db服务实例,这意味着只要请求存在,它就会在请求中使用相同的db上下文实例。如果在对数据库的另一次调用完成之前尝试同步调用db上下文方法,则可能会遇到并发问题,因为上下文的作用域实例将阻止来自其他线程的所有访问,直到操作完成。因此,您需要在限定范围的服务生命周期上下文中使用async/await,或者同步运行所有内容(非常慢)。瞬时生存期在任何时候调用服务时都会创建一个新的实例,因此您不会遇到并发问题,因为它运行在单个线程上。作用域服务被认为是使用依赖关系的一种优化方式,因为您不必在单个客户端请求中不断调用服务提供者来获取上下文的新实例,这会降低性能。当请求或方法完成时,作用域和瞬态都将处理实例。如果您不喜欢我的答案,下面是我找到的一些好文章:,

您如何注入您的dbcontext?您正在执行
services.AddDbContext()
@Bugbeeb services.AddDbContext(选项=>options.UseSqlServer(此处为值)。EnableSensitiveDataLogging(true),ServiceLifetime.Scoped);为什么?我本来想问一个更详细的回答,但这篇文章确实是这样的,非常感谢,当我被允许的时候,我会把你的答案设置为正确的答案。事实上,我更仔细地研究了一下,结果发现我正确地使用了生命周期,问题来自于我将服务放在构造函数中的事实,这就把他们变成了独生子。上面说可以使用invoke,但我真的不知道如何使用它,你能帮我吗?