simpleinjector / SimpleInjector

An easy, flexible, and fast Dependency Injection library that promotes best practice to steer developers towards the pit of success.
https://simpleinjector.org
MIT License
1.21k stars 154 forks source link

Why is SimpleInjectorWebApiDependencyResolver working with async actions #350

Closed pfeigl closed 7 years ago

pfeigl commented 7 years ago

This might sound like a dump title - sorry - but I'm actually wondering how it is working.

We are running a completely async implementation of a WebApi2 stack running on owin. We are using a combination of WebApiRequestLifestyle and SimpleInjectorWebApiDependencyResolver.

Digging through the implementation (as far as I can follow it) SimpleInjectorWebApiDependencyResolver is using BeginExecutionContextScope to create new Scopes on every BeginScope of the IDependencyResolver (which is more or less the "per request" thing).

However, the GetService just runs GetInstance on the container. The created scope is never referenced here, only used for the dispose.

Now, as the complete stack is async and there is no real notion of a request, only of the call to BeginScope, when the owin stack is handling multiple requests at the same time, how does the container actually know, from which scope to resolve instances?

I'm actually asking this question, because we had / have situations, where DbContexts seem to be disposed too early, even while we are definately requesting them in the right scope.

Thanks for any information you can give me on this helping me to understand, how the scope actually works.

Regards, Philipp

dotnetjunkie commented 7 years ago

The ExecutionContextScopingLifestyle uses the CallContext under the covers (and in .NET Core we use AsyncLocal) which gives a local storage for the duration of an async operation, much as ThreadLocal does for a single threaded operation.