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());
        }
    });
  • 相关阅读:
    ant+jenkins+jmeter接口自动化
    fiddler过滤指定的请求
    手机测试
    powerdesign和mysql连接
    testlink安装
    兼容性测试
    sqlserver的事务
    sqlserver中的锁-01
    sqlserve复制
    alwayson10-创建alwayson高可用性组侦听器
  • 原文地址:https://www.cnblogs.com/zzgxl/p/14205170.html
Copyright © 2011-2022 走看看