castleproject / Windsor

Castle Windsor is a best of breed, mature Inversion of Control container available for .NET
http://www.castleproject.org
Apache License 2.0
1.52k stars 456 forks source link

Refs: #646 Castle.Windsor.Extension.DepencencyInjection - No Scope Available #664

Closed AGiorgetti closed 9 months ago

AGiorgetti commented 1 year ago

ExtensionContainerScopeCache.current is an AsyncLocal, AsyncLocal might not be captured in threads originating from Threadpool.UnsafeQueueUserWorkItem.

AspNetCore make heavy use of such threads to optimize performances.

I Added some tests that show supported and unsupported scenarios

I moved the null checks from the AsyncLocal Cache to the scope accessors and improved error messages a bit.

Added an experimental feature to use Castle Windsor standard Singleton lifecycle instead of the custom NetStatic (I believe singletons should always be resolved if you have a container instance whatever the scope is). Enabling it helps me solve singleton resolution issues when the same components are resolved from the IServiceProvider and/or WindsorContainer.

However having "null" for the current scope might be questionable, the Dispose in WindsorScopedServiceProvider rely on that information to correctly cleanup the things (looking at the dotnet DI code, the root scope should be strictly tied to the root service provider). This behavior might still be good because disposing a ServiceProvider resolved/used in a background thread should not dispose the main container anyway.

I think that more changes should be done like:

There was a previous PR (that I closed) similar to this one with less tests and a fix that didn't worked in some scenario, I clsed that and replaced with this one. I think some more changes can be made and a lot of intermediate commits can be squased.

AGiorgetti commented 9 months ago

I am closing this PR because #668 superseeds this one. It also add KeyedServices support