It is necessary to make a factory (easier lambda of course), which would issue a free dbcontext from the pool.

The EF registration looks like this:

services.AddEntityFrameworkMySql().AddDbContextPool<ApplicationDbContext>(options => options.UseMySql(Configuration.GetConnectionString("DefaultConnection")); 

Register lambda like this:

 services.AddTransient<Func<ApplicationDbContext>>(s => s.GetRequiredService<ApplicationDbContext>); 

However, when transferring to some long-living object that accesses the database by an event / timer, I get an exception that the context is already used elsewhere.

 public class SomeService { public SomeService(Func<ApplicationDbContext> dbFact) { this.dbFact = dbFact; } private void DoSomething() { using (var db = dbFact()) { // Do... } } } 

Previously, it worked without a pool of connections, but the result is that a bunch of mysql processes get multiplied in the system. If at the time of the start of the application of processes about 90 in Task Manager, then after a day / two of them it becomes +1400. I think they would continue to multiply if the application did not end due to lack of resources. I open open connection in using, but to see somewhere it all the same is not released.

  • try using a repository. but in your case you need to create a new context every time, then there will be no such problems - pasha goroshko
  • To implement the repository, I still need to declare the base context as a dependency in the repository itself. That is, it will be the same implementation as through lambda only this time I will wrap it in a custom class. What will change? - adrug

0