Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

Is there anything like that in c# / ASP.NET / Azure platform?

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.

like image 248
Ziba Leah Avatar asked Dec 18 '22 09:12

Ziba Leah


1 Answers

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. 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). This is why you have a SaveChanges() method that "commits" everything to the database.

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.

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...

like image 121
JuanR Avatar answered Dec 24 '22 00:12

JuanR