Danger! Dependency Injection Scoped Lifetime and Thread Safety

preview_player
Показать описание
If you're using Scoped Lifetime in a Dependency Injection Container, it's possible to run into race conditions. Here's a simple demo of how. I'm curious, do you used Scoped lifetime by default and do you concern yourself with making objects thread-safe?

💥 Join this channel to get access to source code & demos!

🔥 Don't have the JOIN button? Support me on Patreon!

Рекомендации по теме
Комментарии
Автор

This isn't specifically a threading or thread safe problem, it is an asynchronous problem. The problem you described could still be present in an application running with a single thread.

nicklebeezy
Автор

Excellent video. I think scoped has a place in web apps exactly because of the reasons you mentioned, not everyone is doing Task.WhenAll, not all services have local state. This is a good reminder when you do you need to examine more closely where you are using scoped.

rayfan
Автор

Can you make a one video to explain exactly when to use Scoped vs transient vs singleton. It's pretty much documented every where but no real-world examples

saurabhchauhan
Автор

I don't understand what the scope service has anything to do with the race condition here. The instance variable is not thread safe and should be guarded with lock.

reverser
Автор

I think the problem is not about DI, but about synchronizationcontext and implicit paralelism.

ZdenoTirc
Автор

Scope lifetime is bad because it forces you to constantly think about what will happen to your shared state, what services will modify that state etc. Also it doesn't make sense to me: suppose that I have a service which will be invoked both in a scoped context and in a background job. How should I register it then? Is it transient or scoped? Should I be worried about it's scope when I am designing components?

Tellalca
Автор

I think its a simple matter of if you are wanting to use multi threading / run multiple tasks in parallel. Then don't use a scoped life time, as its doing exactly what it is meant to do, and scope the lifetime of the instance to within its own context, accessing it from multiple contexts is fundamentally not what a scoped lifecycle would be used for.

jamesgregory
join shbcf.ru