Mediatr: Dealing with generic commands/ handlers

Created on 3 Mar 2018  路  1Comment  路  Source: jbogard/MediatR

Hi! I'm trying to do something along the lines of:

Generic commands:
```c#
public class CreateCommand : IRequest where T : Entity, new()
{

}

public class DeleteCommand : IRequest where T : Entity, new()
{
public int Id { get; set; }
}

**Generic handler**
```c#
public class CreateCommandHandler<T> : IRequestHandler<CreateCommand<T>, bool> where T: Entity, new()
{
    public Task<bool> Handle(CreateCommand<T> request, CancellationToken cancellationToken)
    {
        /* Works with T and produces return value */
    }
}

Specific command:
c# public class CreateFooCommand : CreateCommand<Foo> { public string Name { get; set;} }
Today I'm getting:

InvalidOperationException: Handler was not found for request of type. Register your handlers with the container. See the samples in GitHub for examples.

Basically what I want is to have basic operations to work using only one generic handler for each type (CRUD). That way I could just describe the commands for each entity instead of writing a handler too.

PS.: I'm using AutoFac and I'm aware it could be a limitation, although I have searched and found this solution (Related: https://github.com/jbogard/MediatR/issues/96; https://github.com/jbogard/MediatR/issues/69).

Most helpful comment

Update: I finally had more time to dig into it and I came with the following solution:

Generic Handlers/ Commands + AutoFac configuration:
https://gist.github.com/thiagomajesk/9abfb649e58847289b2f65d1994636f2

PS.: I'm doing all the AutoFac registration manually since it's just easier to be explicit for each custom configuration than implement a custom scanner for generic cases as seen here (for StructureMap).

>All comments

Update: I finally had more time to dig into it and I came with the following solution:

Generic Handlers/ Commands + AutoFac configuration:
https://gist.github.com/thiagomajesk/9abfb649e58847289b2f65d1994636f2

PS.: I'm doing all the AutoFac registration manually since it's just easier to be explicit for each custom configuration than implement a custom scanner for generic cases as seen here (for StructureMap).

Was this page helpful?
0 / 5 - 0 ratings