Closed raokun closed 6 months ago
把 IAnalysisService analysisService由构造函数注入 改到下面的method上进行注入。
构造函数注入的服务对象类似单例模式,在服务注册时创建,并会一直存在,如果注入的对象有实现IDispose接口的话,长时间没有访问该路由下的接口,这些对象就会被dispose掉
方法上进行对象注入: `
[Authorize]
public async Task<IResult> TotalAnalysis([FromServices] IAnalysisService analysisService ,[FromBody] AnalysisBaseReq req)
{
var res = await analysisService .TotalAnalysis(req);
return Results.Ok(res);
}
`
注入模式默认类似AddScoped,每次调用该方法,都会执行相应的注入构造产生相应新的(跟对象服务的注入模式有关,如果为AddSingleton,则每次仍旧是同一个对象)实例。
Description
现象
使用minimalapi +EFcore+postgresql 开发的接口,在前端出现同时调用后端接口时报错,dbcontext使用异常。将项目改成MVC的controller后调用接口正常。
期望
对应的依赖注入都是scope,dbcontext的生命周期应该是在一次接口调用时,而其他接口应该在调用时使用新的dbcontext,不应该出现DbContext重复访问的现象。
配置(依赖注入代码)
报错内容:
minimal代码git地址
https://github.com/TerraMours/TerraMours_Gpt_Api/tree/MASAmininalAPI
MVC代码git地址
https://github.com/TerraMours/TerraMours_Gpt_Api
Reproduction Steps
minimal代码git地址
https://github.com/TerraMours/TerraMours_Gpt_Api/tree/MASAmininalAPI
MVC代码git地址
https://github.com/TerraMours/TerraMours_Gpt_Api
代码位置
目前问题出现的api:AnalysisMiniApiService 地址:https://github.com/TerraMours/TerraMours_Gpt_Api/blob/MASAmininalAPI/TerraMours/TerraMours/Domains/LoginDomain/MiniApi/AnalysisMiniApiService.cs 在这个service下的接口会同时调用。会出现上述问题。
Expected behavior
前端并发调用接口时,数据库查询正常
Actual behavior
前端并发调用接口查询数据库时,会出现报错:
Known Workarounds
No response
.NET version
net7.0
MASA Framework version
1.0.1-preview.10
Other information
包引用