Skip to content

Applying decorators conditionally using type constraints #159

@meinsiedler

Description

@meinsiedler

Hi!

We are using Scrutor to apply generic decorators to command handlers and query handlers. This means we have for example a generic ICommandHandler<TCommand> interface and a specific handler implementation which then handles a specific command, e.g. AddPersonCommandHandler : ICommandHandler<AddPerson>.

We apply generic decorators for cross-cutting concerns like transactions, logging, and so on.

Also, we use decorators for permission checks, this looks like this for example:

class AccessValidationCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand>
    where TCommand : IAccessRestricted
{
    private readonly ICommandHandler<TCommand> decoratee;

    public AccessValidationCommandHandlerDecorator(ICommandHandler<TCommand> decoratee)
    {
        this.decoratee = decoratee;
    }

    void ICommandHandler<TCommand>.Handle(TCommand command)
    {
        // Do access validation
        this.decoratee.Handle(command);
    }
}

The decorator in this example uses a generic type constraint for TCommand so that the decorator should only apply to those ICommandHandler<TCommand> implementations where the TCommand implements the IAccessRestricted interface.

We are coming from Simple Injector where this use case is supported and documented here: https://docs.simpleinjector.org/en/latest/aop.html#applying-decorators-conditionally-using-type-constraints

It seems like Scrutor doesn't consider the generic type constraints and tries to apply the decorator to all ICommandHandler<TCommand> implementations regardless of the generic type constraint which leads to an exception on startup because the generic type constraint is not satisfied.

Would it be possible to support that use case and that Scrutor considers the generic type constraints when applying decorators?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions