Trying to understand which service lifetime best for service layer Transient or scoped(WHY). I am looking for pros and cons of using scoped as service layers instead of transient. does Transient service works well with Database Transaction or keeping service layer as scoped is not a good thing to do. Thanks
Usually, you should default to transient lifetimes. These are easy to understand and will generally discourage you from keeping state in your services. It’s also the most compatible lifetime with other services since it can be used from anywhere. So unless you have certain requirements, just choose transient by default.
Scoped services are good when you have expensive operations or temporary state that should be kept for the duration of the request. Database connections are a good example of that because a database connection is not super cheap and using a single connection for handling the single request of a single user (which isn’t happening concurrently) works pretty well. Other examples would be calculated things on top of the request data, e.g. data retrieved from external sources about the user (although here you might even consider a longer living cache).
If you aren’t creating your database connection yourself, chances are that you already have some service through which you will need to go in order to work with the database. This service is then hopefully already registered to be scoped service. An example for this is the DbContext from Entity Framework Core which will be registered as a scoped dependency by default.
If you consume such services, you can consume them from a transient service. Multiple (transient) services will just end up receiving the same instance. But that’s an implementation detail your services shouldn’t bother with. So the default suggestion still counts: Register the service as transient.
When deciding between transient and scoped, it’s also a good idea to consider the following question: Is the service resolve multiple times during the handling of a single request? Is there a problem creating a separate instance each time (e.g. is it an expensive operation)? Then choosing a scoped lifetime may help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With