Skip to content

How can a depending class know if IServiceProvider is Scoped, in order to safely resolve a scoped service if available? #104900

Open
@FrankBakkerNl

Description

@FrankBakkerNl

Sometimes a scoped service needs to be injected into a depending class that is sometimes used inside a scope and sometimes outside a scope. An example would be a Log Enrichter that wants to access data that is only available within a Scope.

When used inside a scope it wants to receive the instance of that specific scope. If the depending class is created from the root scope it is illegal to resolve a scoped service. One way resolve the service from a 'root' IServiceProvider` is to create a new scope on the fly and resolve teh scoped service from that. However the depending class then needs a way of knowing if it needs to create a new scope or not. If it would always create a new scope, it will not receive the correct instance if it was already in a scope.

As far as I can tell, there is currenlty no public API that allowes a consumer of an IServiceProvider to dertermine if it is scoped or not, Except for trying to create the scoped service and catch an exception if it fails, which seems unreliable.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-Extensions-DependencyInjectionneeds-further-triageIssue has been initially triaged, but needs deeper consideration or reconsiderationquestionAnswer questions and provide assistance, not an issue with source code or documentation.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions