多个请求同时发生意外连接状态

时间:2016-06-13 15:59:24

标签: c# dependency-injection entity-framework-6 asp.net-core

我们使用ASP.NET Core和EF6进行数据库请求。 潜在地,多个用户可以在数据库中同时访问。我通过单元测试实现了这种情况:

Parallel.For(0, 10, count => {
    result = userRepo.Sessions.Any(session => session.Token == token);
});

抛出异常:Unexpected connection state. When using a wrapping provider ensure that the StateChange event is implemented on the wrapped DbConnection

这是我完全理解的:代码尝试并行访问具有相同连接的数据库,但在一个请求完成之前关闭连接。好的,但是使用ASP.NET Core和Dependency Injection,可以在2个请求之间共享相同的连接,因此它可能像上面的测试一样崩溃。我们使用AddScoped在DI容器中注册数据库服务。

我的架构中缺少一些东西?

1 个答案:

答案 0 :(得分:0)

经过大量调查后,我们发现了问题。我们缓存了整个C#lambda表达式,它们通过Entity Framework访问数据库,所以从一个HTTP请求到另一个,<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui" xmlns:c="http://java.sun.com/jstl/core" xmlns:pe="http://primefaces.org/ui/extensions"> <h:head> <title>prueba</title> </h:head> <body> <h:form id="mainForm"> <p:growl id="growl" showDetail="true" /> <p:selectOneMenu id="caseSelection" value="#{switchController.value}"> <f:selectItem itemLabel="Default case" itemValue="default" /> <f:selectItem itemLabel="Case 1" itemValue="case1" /> <f:selectItem itemLabel="null" itemValue="#{null}" /> <f:selectItem itemLabel="Case 2" itemValue="case2" /> <p:ajax update="swichWrapper" process="@this" /> </p:selectOneMenu> <p:separator /> <p:outputPanel id="swichWrapper"> <pe:switch id="switch" value="#{switchController.value}"> <pe:defaultCase> Case: Default </pe:defaultCase> <pe:case value="case1"> Case: <p:commandButton id="case1button" actionListener="#{switchController.listener('case1')}" update=":mainForm:growl" value="Call listener with 'case1'" /> </pe:case> <pe:case value="case2"> Case: <p:commandButton id="case2button" actionListener="#{switchController.listener('case2')}" update=":mainForm:growl" value="Call listener with 'case2'" /> </pe:case> <pe:case value="#{null}"> Case: Null </pe:case> </pe:switch> </p:outputPanel> </h:form> </body> </html> 是相同的,这就是抛出这个异常的原因。

相关问题