Skip to content

Clear parameters when tearing down a command - #199

Merged
mgravell merged 2 commits into
mainfrom
clear-parameters-on-teardown
Aug 20, 2026
Merged

Clear parameters when tearing down a command#199
mgravell merged 2 commits into
mainfrom
clear-parameters-on-teardown

Conversation

@mgravell

Copy link
Copy Markdown
Member

Vanilla Dapper's finally blocks all do cmd.Parameters.Clear() before the command is disposed (the "Add-tastic" comments), and it's load-bearing rather than tidy: a parameter object the caller supplied — an ICustomQueryParameter's DbParameter, or one added to DynamicParameters directly — otherwise stays owned by the dead command's collection, and the next use throws "The SqlParameter is already contained by another SqlParameterCollection". That's exactly what the Dapper test suite's TestCustomParameterReuse catches once #198 makes custom parameters work at all.

UnifiedCommand.Cleanup now clears before disposing. Recycled commands keep their parameters, as before — recycling doesn't pass through Cleanup.

Vanilla Dapper's finally blocks all do cmd.Parameters.Clear() before the
command is disposed, and that is load-bearing rather than tidy: a parameter
object the caller supplied - an ICustomQueryParameter's DbParameter, or one
added to DynamicParameters directly - stays owned by the dead command's
collection otherwise, and the next use throws 'The SqlParameter is already
contained by another SqlParameterCollection'. UnifiedCommand.Cleanup now
does the same; recycled commands keep their parameters, as before, since
recycling does not pass through Cleanup.
UnifiedCommand.Cleanup was the wrong (or at least insufficient) place: the
query and execute pipelines dispose the command via SyncCommandState /
AsyncCommandState, which never pass through Cleanup. Recycled commands are
nulled out of the state before Dispose runs, so their parameters are still
kept for in-place update, as before.
@mgravell
mgravell merged commit 16947a8 into main Aug 20, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant