A team wants nightly scenarios to use real databases without giving up parallel execution. Creating a fresh database for every scenario is too costly, but sharing one database lets concurrent scenarios interfere with each other. Resource pooling provides a limited set of reusable databases instead. section 21.2 section 18.7
A pool holds several instances of an external resource. A scenario leases one instance for exclusive use, then returns it when the scenario finishes. Four test workers and four databases, for example, let four database-dependent scenarios run concurrently. The pool size limits how many such scenarios can use the resource at once. section 21.2 section 21.5
A practical pool needs more than a collection of instances:
- Create instances when first requested, so a single-scenario run does not initialize the whole pool. section 21.2
- Make acquisition and release thread-safe: parallel scenarios may request resources at the same time. section 21.2
- Return the instance when its scenario ends, and keep any change-tracking state with that particular instance. section 21.2 section 21.5
Listing 21.3 Context class represents a pooled database
*** Support/DatabaseContext.cs ***
public class DatabaseContext(
IDbContextFactory<WimpDbContext> dbContextFactory) :
IDisposable
{
public IDbContextFactory<WimpDbContext> DbContextFactory =>
dbContextFactory; #A
private int isLeased; #B
internal bool TryLease() => Interlocked.Exchange(ref isLeased, 1) == 0;
internal bool TryRelease() => Interlocked.Exchange(ref isLeased, 0) == 1;
public void Dispose()
{
DatabasePoolDriver.ReleaseDatabase(this); #C
}
} The database context records whether its instance is leased. Its disposal returns that instance to the pool when the scenario finishes. section 21.2
Exclusive access prevents concurrent scenarios from changing the same instance, but it does not erase changes left for the next scenario. Reset the resource as needed before reuse. If a reset can skip unchanged data, record what changed on the context that owns the leased instance. Where multiple identical instances are unavailable, serial execution or exclusive data partitions are other isolation strategies. section 21.2 section 18.7

