I've used "AddDbContextPool" to an dotnetcore console app 2.2 and it looks like it creates the right amount of sessions on the DB but doesn't seem to be utilizing them. Here is my code. Should I use the same context through the entire console or create a new one with every call?
public class Startup
{
private static IConfiguration _iconfiguration;
static string appsettingsFile = @"appsettings.json";
public void ConfigureServices(IServiceCollection services)
{
Console.WriteLine("Configuring Services");
var builder = new ConfigurationBuilder().AddJsonFile(appsettingsFile);
_iconfiguration = builder.Build();
services.AddDbContextPool<MyDBContext>(c => c.UseSqlServer(_iconfiguration.GetSection("DBConnectionString").Value));
}
}
class Program
{
public static IServiceProvider _serviceProvider = null;
static async Task Main(string[] args)
{
var serviceCollection = new ServiceCollection();
var su = new Startup();
su.ConfigureServices(serviceCollection);
_serviceProvider = serviceCollection.BuildServiceProvider();
var t = new Test(_serviceProvider);
var t1 = t.List();
var t2 = t.List();
var t3 = t.List();
await t1;
await t2;
await t3;
}
}
class Test
{
private IServiceProvider _serviceProvider = null;
public Test(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public async Task<List<test_list>> List()
{
using (var serviceScope = _serviceProvider.CreateScope())
{
using (var context = serviceScope.ServiceProvider.GetService<MyDBContext>())
{
return await context.test_list.ToListAsync<test_list>();
}
}
}
}
Should I reuse the scope and context throughout the application to give it better performance? I want that to open up 3 connections to DB at the same time versus 1 at a time.
EDIT:
public class Startup
{
private static IConfiguration _iconfiguration;
static string appsettingsFile = @"appsettings.json";
public void ConfigureServices(IServiceCollection services)
{
Console.WriteLine("Configuring Services");
var builder = new ConfigurationBuilder().AddJsonFile(appsettingsFile);
_iconfiguration = builder.Build();
services.AddDbContextPool<MyDBContext>(c => c.UseSqlServer(_iconfiguration.GetSection("DBConnectionString").Value));
}
}
class Program
{
public static IServiceProvider _serviceProvider = null;
static async Task Main(string[] args)
{
var serviceCollection = new ServiceCollection();
var su = new Startup();
su.ConfigureServices(serviceCollection);
_serviceProvider = serviceCollection.BuildServiceProvider();
var serviceScope = _serviceProvider.CreateScope();
var context = serviceScope.ServiceProvider.GetService<MyDBContext>();
var t = new Test(context);
var t1 = t.List();
var t2 = t.List();
var t3 = t.List();
await t1;
await t2;
await t3;
}
}
class Test
{
private MyDBContext _context = null;
public Test(MyDBContext_context)
{
context = _context;
}
public async Task<List<test_list>> List()
{
return await context.test_list.ToListAsync<test_list>();
}
}