参考:https://stackoverflow.com/questions/10027330/how-to-resolve-autofac-instanceperhttprequest
后台是异步处理,前端使用axios同时发送了两个请求上来,结果报错
Connection must be valid and open.
MySqlException: There is already an open DataReader associated with this Connection which must be closed first.
其实错误的问题在于,异步场景下,自己Resolver的,需要加一个scope
private async Task<ClaimsPrincipal> GetIdentityByToken(HttpActionContext context, long userId)
{
UserIdentity result = null;
// 注意此处要加scope,不能直接用(ILoginService)config.DependencyResolver.GetService(typeof(ILoginService));
// 否则并发时会有错误发生
var config = context.ControllerContext.Configuration;
using (var scope = config.DependencyResolver.BeginScope())
{
var loginService = (ILoginService)scope.GetService(typeof(ILoginService));
result = await loginService.GetUserClaimsIdentity(userId, AppCode);
}
//using (var httpRequestScope = IocConfig.IOCContainer.BeginLifetimeScope("httpRequest"))
//{
// var loginService = httpRequestScope.Resolve<ILoginService>();
// result = await loginService.GetUserClaimsIdentity(userId, AppCode);
//}
if (result != null)
{
var principal = new MyPrincipal(result);
context.ControllerContext.RequestContext.Principal = principal;
return principal;
}
else
{
return null;
}
}
本文探讨了在异步场景下使用Autofac时遇到的并发问题,详细介绍了如何通过添加作用域来避免Connectionmustbevalidandopen及MySqlException错误的发生。
2668

被折叠的 条评论
为什么被折叠?



