简体   繁体   English

ASP.NET WebAPI 2 +实体框架连接缓存的最佳实践

[英]ASP.NET WebAPI 2 + Entity Framework Best Practice for connection caching

I'm trying to figure out the best way to perform operations on my platform with WebAPI and Entity Framework. 我正试图找出使用WebAPI和Entity Framework在我的平台上执行操作的最佳方法。

Right now I'm creating a new connection at every request: in every controller there is an object instantiated and disposed for every Method like. 现在我正在为每个请求创建一个新连接:在每个控制器中都有一个对象被实例化并为每个方法处理。

public class SchedulerController : ApiController
{
    private ApplicationDbContext db = new ApplicationDbContext();

    protected override void Dispose(bool disposing)
    {
        if (disposing)
            db.Dispose();
        base.Dispose(disposing);
    }
}

The creation of the connection for each request is, in my opinion, a complete overhead that affects the performances. 在我看来,为每个请求创建连接是一个影响性能的完整开销。 I know on Java there are some tools (Nutcracker maybe?) that handle a sort of connection pool to reuse the same connection and by this way improve the performance. 我知道在Java上有一些工具(可能是Nutcracker?)处理一种连接池以重用相同的连接,这样可以提高性能。

Is there anything like that in c# / ASP.NET / Azure platform? 在c#/ ASP.NET / Azure平台上有类似的东西吗?

I'd really appreciate also a performance comparison on the request growing number. 我非常感谢请求增长数字的性能比较。

EDIT: this mainly refers to the caching that the DbContext made itself. 编辑:这主要是指DbContext自身的缓存。

I think you are misunderstanding how the Entity Framework works. 我认为您误解了实体框架的工作原理。

The EF uses ADO.NET under the covers, so the connection pooling is actually managed by the provider. EF使用ADO.NET,因此连接池实际上由提供者管理。 You can change the behavior of pooling via connection string. 您可以通过连接字符串更改池的行为。 I believe it reuses connections by default. 我相信它默认重用连接。

The EF also uses a few patterns internally like Unit of Work so it's meant to encapsulate a set of operations (hence the word "context" in the name). EF也在内部使用一些模式,如工作单元,因此它意味着封装一组操作(因此名称中的“上下文”一词)。 This is why you have a SaveChanges() method that "commits" everything to the database. 这就是为什么你有一个SaveChanges()方法“提交”数据库的一切。

Because of this, it is actually recommended that you create a new instance per request in order to guarantee the integrity of the "unit of work" and even then, you should make sure to save your changes in a way that translates to an atomic transaction on the db side of things. 因此,实际上建议您为每个请求创建一个新实例,以保证“工作单元”的完整性,即使这样,您也应该确保以转换为原子事务的方式保存更改在db方面的事情。

What you CAN do however, is only create the instance when you need to, as opposed to having the controller create it on every request. 但是,您可以做的只是在需要时创建实例,而不是让控制器在每次请求时创建实例。 Then again, if you are using Web API chances are you will almost always require access to data so... 再说一次,如果你使用的是Web API,你几乎总是需要访问数据,所以......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM