Skip to content

Feature Request: Support for Open Generic TypeHandler registration #2190

@frozzway

Description

@frozzway

Currently, Dapper does not support registering open generic types for TypeHandler.
This creates a significant maintenance burden and forces developers to violate the DRY principle.

I have a generic TypeHandler that works perfectly for any T, for example, handling HashSet for PostgreSQL arrays:

public class HashSetHandler<T> : SqlMapper.TypeHandler<HashSet<T>>
{
    public override void SetValue(IDbDataParameter parameter, HashSet<T> value)
    {
        // Solves Npgsql issue with IEnumerable parameters
        parameter.Value = value?.ToArray(); 
    }

    public override HashSet<T> Parse(object value)
    {
        if (value is T[] array)
        {
            return new HashSet<T>(array);
        }
        return new HashSet<T>();
    }
}

To use this handler, I am forced to manually register every single closed generic type variation used in the application. This is tedious, error-prone, and clutters the startup configuration:

SqlMapper.AddTypeHandler(new HashSetHandler<Guid>());
SqlMapper.AddTypeHandler(new HashSetHandler<int>());
SqlMapper.AddTypeHandler(new HashSetHandler<string>());
SqlMapper.AddTypeHandler(new HashSetHandler<MyEnum>());
// ... repeated for every new type added to the domain models

Please allow the registration of open generic handlers. Dapper should be able to resolve the concrete handler at runtime if an open generic definition is registered.

Desired API:

SqlMapper.AddTypeHandler(typeof(HashSet<>), typeof(HashSetHandler<>));

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions