Managing Scoped Service Lifecycles with a Singleton Factory in .NET: Best Practices?
Hello everyone,
I'm working on implementing a factory pattern for payment services in a .NET application and I'm unsure about properly managing the lifecycle of services. Here's the relevant part of my code:
And here's how I'm using it in a handler:
The ProviderServiceFactory is registered as a Singleton, while the payment services (like PayPalService) are registered as Scoped.
23 Replies
My question is:
How can I ensure that the scope is properly disposed of after using the service in the Handle method?
Is there a better way to implement this pattern that would better respect the Scoped lifecycle of the services?
Any insights or best practices would be greatly appreciated.
Unknown User•3mo ago
Message Not Public
Sign In & Join Server To View
I mean
if you want to insist on the factory you can register it as scoped, no?
The service provider injected would be scoped to that as well, you could avoid creating a scope yourself.
Unknown User•3mo ago
Message Not Public
Sign In & Join Server To View
scope would be destroyed before even getting the instance, I don't agree with this solution.
Unknown User•3mo ago
Message Not Public
Sign In & Join Server To View
Yeah, that's the issue, I don't know which PaymentProvider Service I need to instantiate each call of method "Handle"
Unknown User•3mo ago
Message Not Public
Sign In & Join Server To View
I tried registering Add<IPaymentService> and that didn't work
will try this
Unknown User•3mo ago
Message Not Public
Sign In & Join Server To View
2 for now, but in the future it is going to be more
Unknown User•3mo ago
Message Not Public
Sign In & Join Server To View
closer to 5-10
Unknown User•3mo ago
Message Not Public
Sign In & Join Server To View
I just need to pass initialization parameters within Initialize:
Unknown User•3mo ago
Message Not Public
Sign In & Join Server To View
hm, I need to do it once, these parameters are store id, store key (for client)
Unknown User•3mo ago
Message Not Public
Sign In & Join Server To View
these parameters don't change, so once per application start, but payment service lifecycle is per request (scoped)
Unknown User•3mo ago
Message Not Public
Sign In & Join Server To View
yes
Unknown User•3mo ago
Message Not Public
Sign In & Join Server To View
parameters that I've passed within Initialize will be fetched from database on each request
I'll register each payment provider service as singleton
and return reference to them using ServiceResolver