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()); } });