question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Example of generic IRequestHandler

See original GitHub issue

Are there any examples to show how to make a generic IRequestHandler?

I can obviously add lots of interfaces such as

public class MainWindowViewModel : BindableBase
,IRequestHandler<MainViewModelPing1, string>
,IRequestHandler<MainViewModelPing2, string>
,IRequestHandler<MainViewModelPing3, SomeOtherClass>

but cannot find any examples of a generic handler to handle different requests and responses in the same handler. Is something like the following possible?

public class MainViewModelPing : IRequest<T>
    {
        public string Message { get; set; }
	public T Data { get; set; }
    }

which would handle something like the following

    public class MainViewModelPing : IRequest<string>
    {
        public string Message { get; set; }
    }

    public class MainViewModelPing : IRequest<string>
    {
        public string Message { get; set; }
	public SomeClass Data { get; set; }
    }

    public class MainViewModelPing : IRequest<SomeOtherClass>
    {
        public string Message { get; set; }
	public SomeClass Data { get; set; }
    }

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:8

github_iconTop GitHub Comments

1reaction
zachpainter77commented, May 10, 2021

I have a similar issue… I was able to resolve it by using AutoFac container. But wished I could have solved it using the default container.

Here is what I did…

Request…

 public class AddNoteCommand<TEntity> : IRequest
        where TEntity : class, INoteEntity
{
    public int ParentId { get; set; }
    public int CurrentUserProfileId { get; set; }
    public string NoteContent { get; set; }
}

Handler

public class AddNoteCommandHandler<TEntity> : IRequestHandler<AddNoteCommand<TEntity>>
        where TEntity : class, INoteEntity, new()
{
    private readonly INoteRepository<TEntity> _repo;
    private readonly ITime _time;

    public AddNoteCommandHandler(INoteRepository<TEntity> repo, ITime time)
    {
        _repo = repo;
        _time = time;
    }
    public async Task<Unit> Handle(AddNoteCommand<TEntity> request, CancellationToken cancellationToken)
    {
        await _repo.Insert(new TEntity
        {
            CreatedByUserId = request.CurrentUserProfileId,
            CreatedDate = _time.Current,
            NoteContent = request.NoteContent,
            ParentId = request.ParentId                
        });

        await _repo.SaveChanges();

        return Unit.Value;
    }
}

Registration with AutoFac

public static ContainerBuilder AddGenericHandlers(this ContainerBuilder builder)
{
    builder.RegisterSource(new ContravariantRegistrationSource());    
    builder.RegisterGeneric(typeof(AddNoteCommandHandler<>)).AsImplementedInterfaces();
    return builder;
}

If anybody knows of a way to do this in the default asp.net core DI container then please show me!

0reactions
zachpainter77commented, Aug 11, 2021

It is my understanding (and I tested this) that explicitly registering the GenericHandlerBase isn’t necessary… If you are going to create concrete handlers for each generic type for that handler then MediatR will find the correct handler without issue…

Here is an example of this: image image

Here is the registration using Default DI Container: image

This works just fine… Now imagine if you had multiple entities, and further more, imagine if you had multiple service dependencies for your handler. While even though you would not have to implement the handle method for each derived handler you still need to create a concrete class that closes the generic type and pass all dependencies to the base constructor… In my opinion that is very tedious to have to do that for every entity and every service dependency… In my opinion it is much simpler to simply register the generic handler via Autofac like I showed above. But if not using a third party DI container then by all means create the concrete handlers… If I couldn’t use a third party di container for whatever reason then I would do it this way…

Cheers.

Read more comments on GitHub >

github_iconTop Results From Across the Web

c# - MediatR generic handlers
Error constructing handler for request of type MediatR.IRequestHandler 2[AT.Messenger.Credentials.Business.Requests.V1.Modeles.HandlerRequest 1[ ...
Read more >
MediatR: Generic Request - Khairuddin Ni'am - Medium
Sometimes, when we use MediatR, we need to use generic request. But, MediatR can't find the required handler because default implementation of ...
Read more >
Mapping generic handler to generic query in MediatR
NET Core 3.1 application and I want use a generic query and a generic request that ... IRequestHandler<GetStandardListItemMapQuery<TEnt>, IDictionary<int, ...
Read more >
Uses of Interface org.apache.wicket.request.IRequestHandler
Package for classes that have generic (protocol independent) support for request cycle processing. org.apache.wicket.request.cycle.
Read more >
How to register open-generic types (Command and ...
I am using the example of eShopOnContainers/Ordering service. ... (they implement IRequestHandler) in assembly holding the Commands builder.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found