We have an endpoint that is using EF and we are continually running into this error:
System.Exception: Was not able to generate the document: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached. ---> System.InvalidOperationException: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
I am curious to know if we are registering the EF Context wrong with the container. We are using MSMQ transport as well
builder.Register(x =>
{
return new DbContext
(
new DbContextOptionsBuilder<DbContext>()
.UseSqlServer(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString)
.Options
);
}).As<LifeDbContext>().InstancePerDependency();
This kind of error is usually caused by a faulty connection management mechanism. What container do you use? This registrations (if I understand it correctly) injects a brand new DbContext along with an open connection to each object that requires it. A connection should be disposed of after usage. Different containers implement resource disposal in different ways but generally if you inject something that implements IDisposable (such as DbContext) to another class and you resolve that other class via DI container, you should also explicitly release that other class after usage. Some DI containers offer the API for releasing components after usage while some use scopes for that.
Autofac should automatically dispose all things injected to the handlers after handler invocation. NServiceBus creates a new scope for each message it processes and message handlers are resolved from that scope. When the message processing is done (all handlers have been executed), NServiceBus disposes the scope which should trigger Autofac resource management system to dispose all injected disposable objects.
You can check if this mechanism works for you by using OnRelease API described here. Put a breakpoint in the OnRelease callback to see if it is called after each handler execution. If so, then your resource leak problem is somewhere else, not in the handlers.