Entity Framework Core 2 β DbContext Pools
Entity Framework Core 2 was released on August 14th. It brought new features.
On this article I will explain one of them: DbContext Pools
Normally when a DbContext is injected somewhere by the dependency injection framework, a new instance is created every time. With this, we can have a pool of instances, 128 by default. It is a performance improvement and it is configured like this (console app example):
var serviceProvider = new ServiceCollection() .AddDbContextPool<AdventureWorksContext>(options => { //options }) .AddScoped<IEfQueries, EfQueries>() .BuildServiceProvider();
.AddDbContext from Entity Framework Core 1 is still implemeted in Entity Framework Core 2.
What kind of improvment to expect ?
Let’s build a Query and let’s see the improvment by using 2 instances of the queries service intantiated by injection dependency system:
public Orders GetOrderById(int id) { return _context.WorkOrders.Select( x => new Orders { Id = x.WorkOrderId, ProductName = x.Product.Name, Quantity = x.OrderQty, Date = x.DueDate }).FirstOrDefault(x => x.Id == id); }
// Using AddDbContext var efqueriesService1 = serviceProvider.GetService<IEfQueries>(); efqueriesService1.GetOrders(); var efqueriesService2 = serviceProvider.GetService<IEfQueries>(); efqueriesService2.GetOrders(); // Using AddDbContextPool var efqueriesService1 = serviceProvider.GetService<IEfQueries>(); efqueriesService1.GetOrders(); var efqueriesService2 = serviceProvider.GetService<IEfQueries>(); efqueriesService2.GetOrders();
I executed this serie of execution 20 times and I measured the execution (using Stopwatch object) this:
With AddDbContext:
- Instance 1: 23 to 29 ms (instantiation + execution)
- Instance 2: 7 to 9 ms (instantiation + execution)
With AddDbContextPool:
- Instance 1: 17 to 21 ms (instantiation + execution)
- Instance 2: 5 to 7 ms (instantiation + execution)
It looks a bit more performant! π