【问题标题】:Cannot access a disposed object Error when Call component two times in a row连续两次调用组件时无法访问已释放的对象错误
【发布时间】:2020-06-25 18:09:15
【问题描述】:

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

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 语句中。如果你是 使用依赖注入,你应该让依赖注入 容器负责处理上下文实例。对象名称: 'KuteCoredbContext

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

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

或者当通过其他groupid调用组件时

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

【问题讨论】:

    标签: entity-framework asp.net-core dependency-injection components dispose


    【解决方案1】:

    我找到了解决办法。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-02
      • 2016-12-06
      • 2020-11-25
      相关资源
      最近更新 更多