Fix some issues with background thread compilation (#42986)
- Resolve dependencies before counting to avoid the race
where its possible for the background thread to run before
the main thread resulting in singletons being resolved during
compilation (it's meant to be side effect free).
- We also avoid capturing the ExecutionContext on the background thread
to avoid capture of async locals.
Fixes dotnet/extensions#3566
Taken from https://github.com/dotnet/extensions/pull/3569/commits/
07e4459b6e81d10c9b3a6561f4cc0fe5a6cbcf8b