发布时间:2020-07-06 17:12:34来源:本站阅读(1107)
开发中我们以常会用到多线程进行操作。
在.net core中 Task里用到上下文时经常会遇到错误
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.
啥意思呢?如下
以上内容来源于翻译软件。
很显然,我们是可以理解到的,上下文是依赖注入进来的, 生命周期也是注入时就定了的。我注入的是ServiceLifetime.Scoped,就是一个请求一个实例。当我们开Task时已经切换了线程,刚才的上下文已经释放了,不能再使用了。就报错了。
这时怎么办呢。我们new一个出来。但真正写代码的时候就不容易了。framework的时候还好点。百度到都是在dbcontext里重写了配置,上下文不注入了。后来还是解决了。
以上是代码。
后来我又想到,如果我把注入和生命周期改下,是不是可以呢,这个需要测试下。完后补充。
下一篇: datetime和datetime2
917
1071
2053
1904
1425
1866
1067
1025
1014
1750
9940
6146
5692
5262
4732
4445
3617
3494
3493
3406