C#C
C#3mo ago
KevS

Generic IH Handlers?

I have a json polymorphic type and I depending on where I'm using it, I want to get a different result type. I have two implementations, the top one works but the bottom one seems cleaner but doesn't work. Are generic handlers possible or do I need to stick to method A here

// THIS ONE WORKS
[Handler]
[AutoConstructor]
public sealed partial class LoadPolymorphObject
{
    private readonly IDbContextFactory<ApplicationDbContext> _dbContextFactory;

    public sealed record Request(int pk, Type targetType);

    private async ValueTask<TObject> HandleAsync(Request request, CancellationToken ct)
    {
        ApplicationDbContext db = await _dbContextFactory.CreateDbContextAsync(ct);
        
        ObjectBase? obj = await db.Table.FindAsync(
            request.pk,
            cancellationToken: ct
        );

        return obj.GetType() == request.targetType
            ? obj
            : throw new InvalidCastException();
    }
}


// THIS ONE DOESNT 
[Handler]
[AutoConstructor]
public sealed partial class LoadPolymorphObject(ApplicationDbContext db)
{
    private readonly IDbContextFactory<ApplicationDbContext> _dbContextFactory;
    public sealed record Request(int pk);

    private async ValueTask<TObject> HandleAsync<TObject>(Request request, CancellationToken ct) where TObject : ObjectBase
    {
        ApplicationDbContext db = await _dbContextFactory.CreateDbContextAsync(ct);
        
        FoundObject? obj = await db.Table.FindAsync(request.pk, cancellationToken: ct
        );

        return obj is TObject ? obj : throw new InvalidCastException();
    }
}
Was this page helpful?