EF Core如何在类实例中获取DBContext?

时间:2019-02-20 08:37:24

标签: asp.net-core dependency-injection

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

从Home控制器的方法中,我调用Task.Run以获取类MyClass的实例的方法,在这里我需要从数据库访问数据。

我试图将_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
   }
}

启动

public void ConfigureServices(IServiceCollection services)
{
  services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

  string connection = Configuration.GetConnectionString("ConnectionDB");
  services.AddDbContext<DataBaseContext>(options =>  options.UseSqlServer(connection));
  // another code
}

能否请您告诉我如何在MyClass实例内部访问dbContext?

1 个答案:

答案 0 :(得分:1)

代码中最重要的错误是您在async void的{​​{1}}方法中使用AnyMethodAsync()。不要在代码中使用Myclass,而应使用async void。详细信息如下:C# – beware of async void in your code

因此,按如下所示编写您的async Task

AnyMethodAsync()

现在,您可以将public async Task AnyMethodAsync() { MyData myData = await _dbContext.AnyData.Where(d => d.id == 1).FirstOrDefault(); } 注册到ASP.NET Core DI容器,如下所示:

MyClass

现在按如下方式使用它:

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