-
Notifications
You must be signed in to change notification settings - Fork 0
Item Factories
The pool creates new items through an IItemFactory<TPoolItem>. Use the built-in factory when the service provider can construct your item; implement your own when construction needs arguments the container cannot express. This guide covers both. The DI registrations appear in the Dependency injection reference.
A factory has one method:
public interface IItemFactory<TPoolItem>
where TPoolItem : class
{
TPoolItem CreateItem();
}The pool calls CreateItem whenever it needs a new instance — to pre-create MinSize items at startup, and to grow toward MaxSize when no idle item is available. Keep construction cheap and free of I/O; defer the expensive connect-or-authenticate work to a preparation strategy, which runs on each lease.
Set UseDefaultFactory = true and the pool resolves TPoolItem from the service provider. Register the item type alongside the pool:
services.AddTransient<SmtpConnection>();
services.AddPool<SmtpConnection>(configuration, options =>
{
options.UseDefaultFactory = true;
});The default factory creates a service scope and resolves the item from it, so scoped dependencies your item needs are honored. Reach for this whenever the container can build your item with no extra arguments.
When construction needs credentials, endpoints, or handcrafted state the container cannot supply, implement IItemFactory<TPoolItem>:
internal sealed class SmtpConnectionFactory(
IOptions<SmtpClientOptions> clientOptions,
TimeProvider timeProvider)
: IItemFactory<SmtpConnection>
{
public SmtpConnection CreateItem() =>
new(CreateTransport, clientOptions.Value, timeProvider);
}Register it with AddPoolItemFactory<TPoolItem, TFactory>(), then add the pool. Leave UseDefaultFactory unset — the custom factory takes its place:
services
.AddPoolItemFactory<SmtpConnection, SmtpConnectionFactory>()
.AddPool<SmtpConnection>(configuration, options =>
{
options.MinSize = 2;
options.MaxSize = 10;
});The factory is registered as a singleton, so any dependencies it captures live for the life of the pool. A full worked factory is in the SMTP connection pool recipe.
- Preparation strategies — do the connect/authenticate work the factory deliberately skips.
- Dependency injection — the full set of registration extensions.