无法访问已释放的对象连续两次调用组件时出错



在我的项目中,我有一个组件,它显示特定组中的产品列表。

public class ProductListIncategoryViewComponent : ViewComponent
{
private IProductRepository productRepository;
public ProductListIncategoryViewComponent(IProductRepository repoprod)
{
productRepository = repoprod;
}
public IViewComponentResult Invoke(int priorityid)
{
MixProductView result = productRepository.SelectByCategory(priorityid);
return View(result);
}
}

组件输入为groupID。

所以我调用组件两次,以显示两组的乘积。例如:

@await Component.InvokeAsync("ProductListIncategory", new { priorityid = 3 })
@await Component.InvokeAsync("ProductListIncategory", new { priorityid = 4 }) //Error 

我连续做两次时出错了。

无法访问已释放的对象。此错误的常见原因是处理从依赖项注入解析的上下文,以及然后稍后尝试在您的应用如果在上下文,或将上下文包装在using语句中。如果你是使用依赖项注入,应该让依赖项注入容器负责处理上下文实例。对象名称:'KuteRedbContext

但调用组件一次时没有错误

@await Component.InvokeAsync("ProductListIncategory", new { priorityid = 3 })

或者当其他groupid 调用组件时

@await Component.InvokeAsync("ProductListIncategory", new { priorityid = 4 })

我找到了解决方案。

我需要在services.AddDbContext之后将此命令添加到startup.cs

services.AddDbContext<KuteCoredbContext>(option => option.UseSqlServer(Configuration["Data:KuteCore:ConnectionString"]));
services.AddTransient<KuteCoredbContext>();// <----add thos command

最新更新