Command pooling
If command is struct, VitalRouter avoids boxing, so no heap allocation occurs. This is the reason of using struct is recommended.
In some cases, however, you may want to use class. Typically, when Command is treated as a collection element, boxing is unavoidable.
So we support the ability to pooling commands when classes are used.
public class MyBoxedCommmand : IPoolableCommand
{
public ResourceA ResourceA { ge; set; }
void IPoolableCommand.OnReturnToPool()
{
ResourceA = null!;
}
}
Rent from pool
// To publish, use CommandPool for instantiation.
var cmd = CommandPool<MyBoxedCommand>.Shared.Rent(() => new MyBoxedCommand());
// Lambda expressions are used to instantiate objects that are not in the pool. Any number of arguments can be passed from outside.
var cmd = CommandPool<MyBoxedCommand>.Shared.Rent(arg1 => new MyBoxedCommand(arg1), extraArg);
var cmd = CommandPool<MyBoxedCommand>.Shared.Rent((arg1, arg2) => new MyBoxedCommand(arg1, arg2), extraArg1, extraArg2);
// ...
// Configure value
cmd.ResourceA = resourceA;
// Use it
publisher.PublishAsync(cmd);
Return to pool
// It is convenient to use the `CommandPooling` Interceptor to return to pool automatically.
Router.Default.Filter(CommandPooling.Instance);
// Or, return to pool manually.
CommandPool<MyBoxedCommand>.Shard.Return(cmd);