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());
        }
    });
  • 相关阅读:
    telnet
    lrzsz工具小问题处理
    1 Boost 安装简介
    klbostee/dumbo
    《笨办法学 C 语言》翻译项目
    关注生成器
    PHP学习之三:变量
    HTML5新书三章大纲分享
    C# 处理 google map 经纬度偏移量
    Jquery 的百度地图应用
  • 原文地址:https://www.cnblogs.com/zzgxl/p/14205170.html
Copyright © 2011-2022 走看看