martinothamar / Mediator

A high performance implementation of Mediator pattern in .NET using source generators.
MIT License
2.14k stars 71 forks source link

[Suggestion] Option to control handler lifetime #60

Open janoveh opened 1 year ago

janoveh commented 1 year ago

What about providing the following interfaces and use those to register handlers accordingly: ISingletonRequestHandler<in TRequest, Tresponse>, IScopedRequestHandler<...>, ITransientRequestHandler<...> All of them inherit from IRequestHandler<...>. Default lifetime applies if IRequestHandler<...> is used. Alternatively, there could maybe be an attribute to override the default registration. In a larger asp.net core web api type of backend you will typically have a mix of lifetimes for your handlers. It would actually also be a good idea for notification handlers, in my opinion.

martinothamar commented 1 year ago

Interesting idea! This needs some prototyping (would need some refactoring), but it would definitely be a nice feature. I agree that it would have to be configurable across all handlers.

Probably will be some challenges/design questions when it comes to combination of handlers and pipelinebehaviors with different lifetimes, but as long as it doesn't become too messy/unclear I think this could work

janoveh commented 1 year ago

Yes, I believe there will probably (?) be some challenges around handling DI scopes and injection of the IMediator service into handlers, especially in singletons, I guess, but I think they can be overcome by carefully creating scopes as needed. But this would of course be the responsibility of the handler developer and not the Mediator source generators. I must say I really like the work you have done on the source generator.