m4ss1m0g / mediatr-ts

Mediator patter for Typescript, inspired to MediatR csharp library
MIT License
50 stars 10 forks source link

Implementing a custom Resolver requires specifc import order #27

Closed brunovinicius closed 2 months ago

brunovinicius commented 2 months ago

When implementing a custom resolver, because the method add is called when the classes are first referenced by an import its a must that we had replaced the resolver with our custom one, it creates the necessity of having the imports in a specific order (first the code that replaces the custom resolver, then the handlers). Otherwise, the custom resolver will miss the add() calls and break at runtime.

This problem manifested for me while implementing a custom resolver to integrate with Angular DI but I imagine this to be true to any custom implementation.

I believe that in order to fix this Resolver could simply expose a factoryFn that is called when we need to instantiate the handler class. This could be elevated furthermore by hiding the resolver completely in favor of this simple function. With this, since the default resolver would always keep the map of command names to handlers within itself, no import sort order problem would arise.

I speculate we could push it further and say that implementing custom resolvers could be completely deprecated in favour of implementing this factoryFn to integrate with any DI, requiring it to only serve as a factory for the handlers mediatr-ts needs. The drawback of this is that it would break backwards compatibility.

I took the liberty of providing a simple PR with the suggested implementation. Would appreciate feedback.

m4ss1m0g commented 2 months ago

Try to view if the PR#26 resolves the issue. WARNING It is a major release.

brunovinicius commented 2 months ago

Thanks for the response @m4ss1m0g The short answer to your question is "no" I wrote the long version on the PR so @ffMathy can chime in