Asp.net core EF Core如何在类实例中获取DBContext?

Asp.net core EF Core如何在类实例中获取DBContext?,asp.net-core,dependency-injection,Asp.net Core,Dependency Injection,ASP NET核心项目使用实体框架核心 从主控制器的方法中,我调用Task.Run作为类MyClass实例的方法,在这里我需要从数据库访问数据 我试图将\u dbContext传递给MyClass类的构造函数,但得到了异常 无法访问已释放的对象 HomeController [Route("api/[controller]")] [EnableCors("AllowAllOrigin")] [ApiController] public class HomeController : Control

ASP NET核心项目使用实体框架核心

从主控制器的方法中,我调用Task.Run作为类
MyClass
实例的方法,在这里我需要从数据库访问数据

我试图将
\u dbContext
传递给
MyClass
类的构造函数,但得到了异常

无法访问已释放的对象

HomeController

[Route("api/[controller]")]
[EnableCors("AllowAllOrigin")]
[ApiController]
public class HomeController : ControllerBase
{
   private readonly DataBaseContext _dbContext;

   public HomeController (DataBaseContext dbContext)
   {
      _dbContext = dbContext;
   }

   [EnableCors("AllowAllOrigin")]
   [HttpPost("[action]")]
   public string UpdateBotSettings()
   {
      MyClass myClass = new MyClass(_dbContext);
      Task task = Task.Run(() => myClass.AnyMethod());
   }
}
MyClass

public class MyClass
{
   private readonly DataBaseContext _dbContext;

   public MyClass(DataBaseContext dbContext)
   {
      _dbContext = dbContext;
   }

   public async void AnyMethodAsync()
   {
      MyData myData = _dbContext.AnyData.Where(d => d.id == 1).FirstOrDefault(); // <- exception
   }
}
公共类MyClass
{
私有只读数据库上下文_dbContext;
公共MyClass(DataBaseContext dbContext)
{
_dbContext=dbContext;
}
公共异步void AnyMethodAsync()
{
MyData MyData=_dbContext.AnyData.Where(d=>d.id==1.FirstOrDefault();//options.UseSqlServer(连接));
//另一个代码
}

您能告诉我如何在MyClass的实例中访问dbContext吗?

代码中最重要的错误是您在
AnyMethodAsync()中使用了
async void
Myclass的方法
。不要在代码中使用
async void
,而是使用
async Task
。以下是详细信息:

因此,请按如下方式编写
AnyMethodAsync()

public async Task AnyMethodAsync()
{
   MyData myData = await _dbContext.AnyData.Where(d => d.id == 1).FirstOrDefault(); 
}
public void ConfigureServices(IServiceCollection services)
{
   services.AddScoped<MyClass>(); // <-- here it is

   string connection = Configuration.GetConnectionString("ConnectionDB");
   services.AddDbContext<DataBaseContext>(options =>  options.UseSqlServer(connection));
   // another code
   services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
[Route("api/[controller]")]
[EnableCors("AllowAllOrigin")]
[ApiController]
public class HomeController : ControllerBase
{
   private readonly DataBaseContext _dbContext;
   private readonly MyClass _myClass

   public HomeController (DataBaseContext dbContext, MyClass myClass)
   {
      _dbContext = dbContext;
      _myClass = myClass;
   }

   [EnableCors("AllowAllOrigin")]
   [HttpPost("[action]")]
   public async Task<string> UpdateBotSettings()
   {
      await _myClass.AnyMethod();

      // rest of codes
   }
}
现在,您可以将
MyClass
注册到ASP.NET Core DI容器,如下所示:

public async Task AnyMethodAsync()
{
   MyData myData = await _dbContext.AnyData.Where(d => d.id == 1).FirstOrDefault(); 
}
public void ConfigureServices(IServiceCollection services)
{
   services.AddScoped<MyClass>(); // <-- here it is

   string connection = Configuration.GetConnectionString("ConnectionDB");
   services.AddDbContext<DataBaseContext>(options =>  options.UseSqlServer(connection));
   // another code
   services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
[Route("api/[controller]")]
[EnableCors("AllowAllOrigin")]
[ApiController]
public class HomeController : ControllerBase
{
   private readonly DataBaseContext _dbContext;
   private readonly MyClass _myClass

   public HomeController (DataBaseContext dbContext, MyClass myClass)
   {
      _dbContext = dbContext;
      _myClass = myClass;
   }

   [EnableCors("AllowAllOrigin")]
   [HttpPost("[action]")]
   public async Task<string> UpdateBotSettings()
   {
      await _myClass.AnyMethod();

      // rest of codes
   }
}
public void配置服务(IServiceCollection服务)
{
services.addScope();//options.UseSqlServer(连接));
//另一个代码
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
现在按如下方式使用它:

public async Task AnyMethodAsync()
{
   MyData myData = await _dbContext.AnyData.Where(d => d.id == 1).FirstOrDefault(); 
}
public void ConfigureServices(IServiceCollection services)
{
   services.AddScoped<MyClass>(); // <-- here it is

   string connection = Configuration.GetConnectionString("ConnectionDB");
   services.AddDbContext<DataBaseContext>(options =>  options.UseSqlServer(connection));
   // another code
   services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
[Route("api/[controller]")]
[EnableCors("AllowAllOrigin")]
[ApiController]
public class HomeController : ControllerBase
{
   private readonly DataBaseContext _dbContext;
   private readonly MyClass _myClass

   public HomeController (DataBaseContext dbContext, MyClass myClass)
   {
      _dbContext = dbContext;
      _myClass = myClass;
   }

   [EnableCors("AllowAllOrigin")]
   [HttpPost("[action]")]
   public async Task<string> UpdateBotSettings()
   {
      await _myClass.AnyMethod();

      // rest of codes
   }
}
[路由(“api/[控制器]”)]
[使能公司(“AllowAllOrigin”)]
[ApiController]
公共类家庭控制器:ControllerBase
{
私有只读数据库上下文_dbContext;
私有只读MyClass\u MyClass
公共HomeController(DataBaseContext dbContext,MyClass MyClass)
{
_dbContext=dbContext;
_myClass=myClass;
}
[使能公司(“AllowAllOrigin”)]
[HttpPost(“[行动]”)]
公共异步任务UpdateBotSettings()
{
wait_myClass.AnyMethod();
//其余代码
}
}

您能否发布Startup.cs中显示DbContext在哪个作用域下的代码片段?由添加。在控制器内部,数据上下文运行时不会出错。可能在任务运行时,上下文已被释放。为什么不使控制器操作
异步
并使用您的服务,而无需创建新的
任务
?@IvanMladenov根据需要从控制器中删除部分逻辑。这就像使用
服务定位器
反模式,这有点扼杀依赖反转的目的是的!我只是给了他解决问题的方法。否则我建议构造函数DI注入。@TanvirArjel有可能了解更多abo吗ut构造器DI注入?@al.koval请查看我的更新答案,我给您提供了一些在ASP.NET Core中研究DI的链接。@al.koval您可以主要阅读以下内容: