Skip to content

Conversation

@7amou3
Copy link

@7amou3 7amou3 commented Jul 20, 2025

This PR represents an attempt to resolve issue #159.

The prior approach of the source generator (#117) inadvertently led to the generation of code that instantiated a new TypeHandler object for each parameter or column read operation (new global::CustomClassTypeHandler().Read(...)). This could lead to unnecessary object allocations and a minor performance overhead, especially in high-volume scenarios.

This PR introduces a TypeHandlerInstanceRegistry and modifies the code generation to ensure that:

  • A single, static instance of each registered TypeHandler is created within the generated interceptor file (e.g., __Handler1, __Handler2).
  • All subsequent operations (setting parameters, parsing output parameters, reading result set columns) for a given type handler utilize this pre-allocated, static instance.

// Example using a module-level attribute
using Dapper;

[module: TypeHandler<YourDotNetType, YourCustomTypeHandler>]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I have a query that required certain set of typeHandlers,
And other do not,
Then how to restore them, and then add if and when needed ?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hello, this PR does not currently allow for switching or disabling type handlers on the fly.
This is definitely a feature that could be added, though.

@martinflorek
Copy link

Any update on this PR or #117? I am debugging custom Dapper.AOT TypeHandler for days and it looks like they don't work at all in the lastest Dapper,AOT 1.0.48?

I have registered them via

[module: DapperAot]
[module: TypeHandler<MyCustomType?, MyCustomTypeHandler>]

and they are not used in source generation and I just get runtime cast errors when loading data from DB "Invalid cast from 'System.Int64' to 'MyCustomType'."

What is the purpose of [module: TypeHandler<MyCustomType?, MyCustomTypeHandler>], am I misunderstanding its purpose?

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.

3 participants