当预期单个时,MediatR会获得多个处理程序实例(MediatR gets multiple handlers instances when expected single)

编程入门 行业动态 更新时间:2024-10-28 03:25:58
当预期单个时,MediatR会获得多个处理程序实例(MediatR gets multiple handlers instances when expected single)

我正在使用通用类型请求和处理程序。 如果我有多个IAsyncRequestHandler,DryIoc正在解析多个实例,而不是单个实例,导致MediatR抛出异常。 我怎么解决这个问题? 请在此处查看Net Fiddle的此行为。 (请注意,在此示例中,Generic Type仅用于证明该点 - MediatR抛出异常 - 在我的生产代码中,实际上需要通用类型)

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)

最满意答案

DryIoc 2.10.1解决了您的问题。

细节问题的原因在于#446 。

更新:

关于具有class GoodMorningRequestHandler<T> : IAsyncRequestHandler<GoodMorningRequest, string>示例class GoodMorningRequestHandler<T> : IAsyncRequestHandler<GoodMorningRequest, string>该异常有点误导,但它在此处按预期方式进行。

原因是DryIoc RegisterMany根本没有注册上面的映射。 这是因为RegisterMany检查服务类型( IAsyncRequestHandler<GoodMorningRequest, string> )应该为实现GoodMorningRequestHandler<T>提供开放通​​用参数T ,显然它不能这样做。 因此,此服务类型被过滤掉。

之后,剩下的实现将是HelloRequestHandler<T> ,它与已解析的IAsyncRequestHandler<GoodMorningRequest, string>不匹配,因此异常。

要确认自己尝试只是明确注册:

container.Register(typeof(IAsyncRequestHandler<GoodMorningRequest, string>), typeof(GoodMorningRequestHandler<>)) 。 它会抛出异常。 相比之下, RegisterMany设计得更宽容,因此它只会跳过这一对。

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.

更多推荐

本文发布于:2023-04-28 16:17:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1332454.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   实例   程序   MediatR   multiple

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!