如何在asp.net core和ef7中的并行方法中使用注入的DbContext? [英] How to use injected DbContext in parallel methods in asp.net core and ef7?

查看:217
本文介绍了如何在asp.net core和ef7中的并行方法中使用注入的DbContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有EF7的Asp.net 5/Core 1应用程序.我通常在DI容器中注册DbContext.

I have an Asp.net 5/Core 1 application with EF7. I register the DbContext in the DI container normally.

services.AddEntityFramework().AddSqlServer()
  .AddDbContext<MyDbContext>(options => options.UseSqlServer(connection));

这是一个小样本,显示我正在尝试做的事情.

Here is a small sample showing what I'm trying to do.

public class MyController : Controller
{
    MyDbContext _myDbContext;

    public MyController(MyDbContext myDbContext)
    {
        _myDbContext = myDbContext;
    }

    public IActionResult Index()
    {
        //Just start these and don't wait for them to finish
        //We don't care if they succeed or not
        Task.Run(() => DoSomeLogging1());
        Task.Run(() => DoSomeLogging2());

        return View();
    }

    private void DoSomeLogging1()
    {
        _myDbContext.Items.ToList();
    }

    private void DoSomeLogging2()
    {
        _myDbContext.Items.ToList();
    }
}

两个DoSomeLoggingX方法都将使用注入到控制器的MyDbContext实例.由于这些方法是同时运行的,因此会同时执行db查询,因此另一个方法总是会失败,

Both DoSomeLoggingX methods will use the MyDbContext instance that was injected to the controller. Since the methods are run at the same time doing db queries at the same time, the other one will invariably fail with

连接未关闭.连接的当前状态是 连接.

The connection was not closed. The connection's current state is connecting.

MyDbContext还使用DI来获取一些引用,因此即使我愿意也无法直接使用它.

MyDbContext also uses DI to get some references so I can't use it directly even if I wanted.

如何并行运行代码,仍然能够通过实体框架使用数据库?

How can I run code in parallel and still be able to use my database through entity framework?

推荐答案

我也遇到了这个问题,现在我使用临时解决方案 EF 7(核心).创建类似AddTransient的DBContext

I also faced with this problem and for now I use my temporary solution EF 7 (Core). Create DBContext like AddTransient

如果有人可以提供更优雅的解决方案,我将不胜感激.有时我真的需要将即时结果返回给用户,在这种情况下,await/async不适合

If someone can provide more elegant solution I will be appreciated. Sometimes I really need to return instant result to user and in such cases await/async does not suit

这篇关于如何在asp.net core和ef7中的并行方法中使用注入的DbContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆