👩🏻💻 프로그래밍/C#
[EntityFramework] DbContext 풀링
뽀도
2024. 7. 1. 17:17
- 컨텍스트 풀링을 사용하면 컨텍스트 설정 비용을 지속적으로 지불하지 않고 프로그램 시작 시 한 번만 지불하면 됨.
- 컨텍스트 풀링은 데이터베이스 드라이버에서 하위 수준에서 관리되는 데이터베이스 연결 풀링과 직교한다는 점에 유의
▶ 종속성 주입
builder.Services.AddDbContextPool<WeatherForecastContext>(
o => o.UseSqlServer(builder.Configuration.GetConnectionString("WeatherForecastContext")));
▶ 종속성 주입없이
var options = new DbContextOptionsBuilder<PooledBloggingContext>()
.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0")
.Options;
var factory = new PooledDbContextFactory<PooledBloggingContext>(options);
using (var context = factory.CreateDbContext())
{
var allPosts = context.Posts.ToList();
}
※ poolSize 생성자의 매개변수는 풀이 PooledDbContextFactory보유하는 최대 인스턴스 수를 설정합니다(기본값은 1024). 초과 poolSize되면 새 컨텍스트 인스턴스가 캐시되지 않고 EF는 요청 시 인스턴스를 생성하는 비풀링 동작으로 대체됩니다.
본문)