Search code examples
dryiocmediatr

MediatR gets multiple handlers instances when expected single


I'm using Generic Type Requests and Handlers.
If I have more than one IAsyncRequestHandler DryIoc is resolving multiple instances, instead of a single instance, causing MediatR to throw an exception.
How can I solve this problem?

Please check this behavior at Net Fiddle here.
(Note that in this example Generic Type is only used to prove the point - MediatR throwing the exception - In my production code, Generic Types are actually needed)


Solution

  • The fix for your problem is out with DryIoc 2.10.1.

    The reason details are in issue #446.

    Update:

    Regarding sample with class GoodMorningRequestHandler<T> : IAsyncRequestHandler<GoodMorningRequest, string> the exception is bit misleading but it is here as expected.

    Reason is that above mapping is not registered at all by DryIoc RegisterMany. It happens because RegisterMany checks that service type (IAsyncRequestHandler<GoodMorningRequest, string>) should supply open-generic parameter T for implementation GoodMorningRequestHandler<T>, and obviously it cannot do that. Therefore this service type is filtered out.

    After that, the remaining implementation would be HelloRequestHandler<T> which does not match to resolved IAsyncRequestHandler<GoodMorningRequest, string>, so the exception.

    To confirm for yourself try to just register explicitly:

    container.Register(typeof(IAsyncRequestHandler<GoodMorningRequest, string>), typeof(GoodMorningRequestHandler<>)). It will throw the exception. In comparison RegisterMany designed to be more tolerant, therefore it will just skip this pair.