问题来自博问的一个提问 .net core 多线程数据保存的时候DbContext被释放 。

TCPService 通过构造函数注入了 ContentService , ContentService 的实例依赖了 AppDbContext (继承自 EF Core 的 DbContext)。在 TCPService 中通过 Thread.Start 启动了一个新的线程执行了 TCPService 中的 Receive 方法,在 Receive 方法中通过 ContentService 进行保存数据库的操作,而在访问 AppDbContext 的实例时出现对象已被 Disposed 的错误。

Object name: 'AppDbContext'. --->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.

针对这个问题,尝试改为通过构造函数注入 IServiceProvider ,在 TCPService.Receive (在新线程中执行的方法)中通过 IServiceScope 解析

using (var scope = _serviceProvider.CreateScope())
{
var contentService = scope.ServiceProvider.GetRequiredService<ContentService>();
//...
}

结果发现 IServiceProvider 也被 Disposed

System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'IServiceProvider'.

由此可以推断在 ASP.NET Core 中在新建的线程中无法通过依赖注入的方式访问实现了 IDisposable 接口的对象(单例对象除外,但实现 IDisposable 接口的类型通常不会注册为单例),也就是只要请求一结束,实现 IDisposable 接口的对象的 Dispose 方法就会被调用。

那如何解决这个问题呢?

1)最下下策的解决方法是将 DbContext 注册为单例

services.AddDbContext<AppDbContext>(options => { }, ServiceLifetime.Singleton);

它会带来很多副作用,不考虑。

2)在保存数据至数据库的实现方法中基于 DbContextOptions (它是单例)手工 new AppDbContext ,用这个 DbContext 实例进行保存操作。

public class ContentService : Repository<Content>
{
private readonly DbContextOptions _options; public ContentService(AppDbContext Context, DbContextOptions options) : base(Context)
{
_options = options;
} public override async Task<bool> SaveAsync(Content entity)
{
using (var context = new AppDbContext(_options))
{
context.Set<Content>().Add(entity);
return await context.SaveChangesAsync() > ;
}
}
}

实测有效。

ASP.NET Core 新建线程中使用依赖注入的问题的更多相关文章

  1. ASP.NET Core - 在ActionFilter中使用依赖注入

    上次ActionFilter引发的一个EF异常,本质上是对Core版本的ActionFilter的知识掌握不够牢固造成的,所以花了点时间仔细阅读了微软的官方文档.发现除了IActionFilter.I ...

  2. ASP.NET Core 1.0 中的依赖项管理

    var appInsights=window.appInsights||function(config){ function r(config){t[config]=function(){var i= ...

  3. 在.NET Core控制台程序中使用依赖注入

    之前都是在ASP.NET Core中使用依赖注入(Dependency Injection),昨天遇到一个场景需要在.NET Core控制台程序中使用依赖注入,由于对.NET Core中的依赖注入机制 ...

  4. dotnet core在Task中使用依赖注入的Service/EFContext

    C#:在Task中使用依赖注入的Service/EFContext dotnet core时代,依赖注入基本已经成为标配了,这就不多说了. 前几天在做某个功能的时候遇到在Task中使用EF DbCon ...

  5. Asp.Net Core 第04局:依赖注入

    总目录 前言 本文介绍Asp.Net Core中默认的依赖注入(DI)模式. 环境 1.Visual Studio 2017 2.Asp.Net Core 2.2 开局 第一手:依赖注入说明 1.一个 ...

  6. ASP.NET Core应用的7种依赖注入方式

    ASP.NET Core框架中的很多核心对象都是通过依赖注入方式提供的,如用来对应用进行初始化的Startup对象.中间件对象,以及ASP.NET Core MVC应用中的Controller对象和V ...

  7. ASP.NET Core 配置文件(无处不在的依赖注入)

    前烟: .NET Core 中取消了以往的 XML 节点配置文件,改用了 *.json 格式. 在 Startup.cs 文件中,构造方法 build appsetting.json 文件, 本文主要 ...

  8. asp.net core 系列之Dependency injection(依赖注入)

    这篇文章主要讲解asp.net core 依赖注入的一些内容. ASP.NET Core支持依赖注入.这是一种在类和其依赖之间实现控制反转的一种技术(IOC). 一.依赖注入概述 1.原始的代码 依赖 ...

  9. ASP.NET Core MVC 控制器创建与依赖注入

    本文翻译自<Controller activation and dependency injection in ASP.NET Core MVC>,由于水平有限,故无法保证翻译完全准确,欢 ...

随机推荐

  1. ignitius and princess 2(全排列)

    A - Ignatius and the Princess II Now our hero finds the door to the BEelzebub feng5166. He opens the ...

  2. java----String解析

    String在内存中的分析: public class Demo { public static void main(String[] args){ String a = new String(&qu ...

  3. bzoj 4816

    这题是莫比乌斯反演的典型题也是很有趣的题. 题意:求,其中f为为斐波那契数列 那么首先观察一下指数,发现是我们熟悉的形式,可以转化成这样的形式: 令T=kd,且假设n<m,有: 令 则原式= 这 ...

  4. bzoj 2761

    神题... 其实这题巨水,用各种诡异的方法都能A,包括STL等等 我之所以写题解,是因为我发现了一个bug:bz和luogu时限有问题! 这题我用了两种做法: ①:直接使用STL-map(不能直接用数 ...

  5. 2017-2018-2 20165314实验二《Java面向对象程序设计》实验报告

    实验报告封面 实验一 实验要求 参考 http://www.cnblogs.com/rocedu/p/6371315.html#SECUNITTEST 完成单元测试的学习提交最后三个JUnit测试用例 ...

  6. C++ gethostname()

    使用“gethostname();”获取计算机名,先看源码: 在Code::Blocks 16.01中,设置project的Build options...,Debug > Linker set ...

  7. less 写关键帧动画

    @keyframes 关键帧动画写在less里的时候,务必要写在所有的{}之外,不能被{}包裹 甚至务必写在代码的最后 不然报错 Compilation resulted in incorrect C ...

  8. CAS单点登录--转载

    一:单点登录介绍 单点登录( Single Sign-On , 简称 SSO )是目前比较流行的服务于企业业务整合的解决方案之一, SSO 使得在多个应用系统中,用户只需要 登录一次 就可以访问所有相 ...

  9. Windows Azure 搭建网络代理 Proxy

    额 题目起的有点大 其实就是在 Linux 上使用代理 不过是用的 Azure 上的 Liunx 虚拟机而已 如何在 Azure 上搭建 VPN 见上篇:http://www.cnblogs.com/ ...

  10. AtCoder Regular Contest 101

    C题是个傻逼题, 一定是先向右,然后停了或者向左走到某一个点(左边同理)模拟就可以了 D题想了一会才想出来 和tjoi那道排序挺像的 二分答案变0/1来做 刚开始写的时候还把自己作为另外一类搞出来 这 ...