• 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());
        }
    });
  • 相关阅读:
    JPA报错 javax.persistence.EntityNotFoundException: Unable to find XX类 with id xx问题
    Spring-Data-JPA api文档
    一道小数数学题
    pycharm 关联py之后sqlmap的使用
    base64和base32替换编码解密
    Mysql 启动失败
    Xshell连接linux时常见问题
    使用metasploit 框架保持持久性
    获得shell 、启用远程服务
    Java Class Loader
  • 原文地址:https://www.cnblogs.com/zzgxl/p/14205170.html
Copyright © 2020-2023  润新知