Neat trick for Scoped services in ASP.NET Core
Вставка
- Опубліковано 7 чер 2024
- In this video I demonstrate a small service you can create instead of reaching for an IServiceProvider or an IServiceScopeFactory whenever you need a new scope for your services.
Support my Work 🤝 / raw_coding
Buy my Courses 📚 learning.raw-coding.dev
Buy my Merch 🛒 shop.raw-coding.dev
Join the Community 💬 / discord
Tweet Tweet 📣 / anton_t0shik
Tune in LIVE! 🎥 / raw_coding
#aspnetcore #csharp
The beard -- is just simply spectacular. Hats off to you sir!
I shave before I go to bed
@@RawCodingthat depends where 😅😂
Nice!
Won't this create a new scope per Scoped resolved? So in order to keep the same initial sub-scope but resolve multiple different services from it would require some tweaks.
It feels more like transient, or is it just me? @RawCoding, what do you think?
I was thinking the same, haven't tried it but don't you have to:
a) register the service as transient or
b) create a scope each time in the setter?
for this to work
Thats actually the good part, this trick will force you to create a service that encompasses this scoped operation.
This was great, but I also agree with the question, what if your endpoint needed a GuidService and a TimerService?
Wouldn’t it be better if only one scope was created and disposed rather than two distinct scopes for the same block of code?
Or would that case be something which would just be better handled by manually creating a scope and resolving the services yourself?
At this point I come here just to see the state of the hair and beard 😂
Can make a video explaining scopes. What usually 'starts' a scope? Are scopes only for DI?
You can create a scope yourself (like in the video) but if you create a (minimal) api, the app will create a scope for you for each request. Scopes are only usefull for DI
This method is flawed. For bigger than to-do projects, you need to use multiple services at once, either 1. Always create classes with 1 method for each combination that you need in order to do the job, or 2. Create god service and misuse. Keep in mind that things like transactions and other states need to coexist sometimes to do the job, and being "clean" does not mean being useful. Don't overcomplicate things, just use the scope when you need multiple services, and are doing logic cross lifetimes.
Creating a dedicated class for an operation is a flaw? And I dont get your second point.
So talking about transactions, if you create this scoped operation as a dedicated class without a transaction you can now wrap it in a transaction, and you have an option of running it in or without a transaction, in or without a dedicated scope.
All of this is ofcourse “if you need it”