[Suggestion] Option to control handler lifetime
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.
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
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.
Any status on this?
I'm not really a fan of different marker interfaces in this case... could it be controlled at the handler-level with an attribute, similar to MediatorOptionsAttribute (only, with a class target and lacking the Namespace property)?
Most of our handlers are registered as Transient for "reasons", but we have a handful that we'd like to register as singletons because they are heavy use and don't need anything scoped... it'd be nice to be able to indicate we wanted those particular ones to be registered differently, without cluttering service registrations ourselves.
Not really, this hasn't come up much and I haven't had the need personally. I tend to go all in on Singleton :)
Shame. The majority of our handlers require a db context and thus a scope. Changing them all over to DbContextFactory isn't something we can do in the short term... There's just too many of them and thousands of tests we'd have to rewrite. But if we could gradually make the shift it would be the best of both worlds.
Would you accept a PR that implemented some form of opt-in?
Yeah totally understandable. Would accept a PR yes. I like your idea of using an attribute on the handlers