jbogard / MediatR

Simple, unambitious mediator implementation in .NET
Apache License 2.0
10.91k stars 1.16k forks source link

System.Reflection.AmbiguousMatchException thrown in ServiceRegistrar #974

Closed CommitedSajmon closed 6 months ago

CommitedSajmon commented 8 months ago

Registering services using AddMediatRClasses(IServiceCollection services, MediatRServiceConfiguration configuration) throws System.Reflection.AmbiguousMatchException at handlerType.GetInterface(handlerInterface.Name)

https://github.com/jbogard/MediatR/blob/6baaeef7a16ca75cb905829f870f79c6334ef40e/src/MediatR/Registration/ServiceRegistrar.cs#L132C56-L132C68

private static bool IsMatchingWithInterface(Type? handlerType, Type handlerInterface)
  {
      if (handlerType == null || handlerInterface == null)
      {
          return false;
      }

      if (handlerType.IsInterface)
      {
          if (handlerType.GenericTypeArguments.SequenceEqual(handlerInterface.GenericTypeArguments))
          {
              return true;
          }
      }
      else
      {
          return IsMatchingWithInterface(handlerType.GetInterface(handlerInterface.Name), handlerInterface);
      }

      return false;
  }

The exception is thrown when certain conditions are met:

public record SampleRequest() : IRequest;
public record SampleRequest2() : IRequest;

public class Handler1 : IRequestHandler<SampleRequest>
{
   // rest of code
}

public class Handler2 : IRequestHandler<SampleRequest2>
{
   // rest of code
}

public class Handler3 :  IRequestHandler<SampleRequest>, IRequestHandler<SampleRequest2>
{
   // rest of code
}

Below call typeof(Handler3).GetInterface(typeof(IRequestHandler<SampleRequest>).Name) throws the beforementioned System.Reflection.AmbiguousMatchException as Handler3 is a type that implements the same generic interface "IRequestHandler`1" with different type arguments

I am aware that IRequest is being sent to exactly one IRequestHandler, but the real use case is deprecating Handler1 and Handler2 in favor of the new Handler3. Adding Handler3 to assembly shouldn't break the whole MediatR registration

github-actions[bot] commented 6 months ago

This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 14 days.

github-actions[bot] commented 6 months ago

This issue was closed because it has been stalled for 14 days with no activity.