zoukankan      html  css  js  c++  java
  • EF Core通过上下文注入后在Task中使用问题解决

    直接调用:

    Task.Run(() =>
            {
                try
                {
                    var one = _dataContext.Student.FirstOrDefault(n =>n.Id == 5);
                    // write to other
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            });

    炸了,报错:

    System.ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
          Object name: 'MainDbContext'.

    使用官方例子,方法如下:

    Task.Run(() =>
    {
        try
        {
            var optionsBuilder = new DbContextOptionsBuilder<MainDbContext>();
            // appConfiguration.MySQLString appConfiguration是配置类,MySQLString为连接字符串
            optionsBuilder.UseMySql(appConfiguration.MySQLString);
            using (var context = new MainDbContext(optionsBuilder.Options))
            {
                var one = context.Student.FirstOrDefault(n => n.Id == Id);
                // 当然你也可以直接初始化其他的Service
                var sService = new StudentService(context,null);
                var one =sService.FindOne(Id);
            }
    
        }catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    });
  • 相关阅读:
    数据分析三剑客numpy pandas Matplotlib
    算法 初识
    python 爬虫二
    python 爬虫一
    python celery
    elasticsearch 学习
    ansible 基本使用
    面试题
    奇技淫巧
    【前端基础】- CSS 1-CSS选择器
  • 原文地址:https://www.cnblogs.com/zzgxl/p/14205170.html
Copyright © 2011-2022 走看看