.NET: How do I configure one of my own scoped services to be accessed statically?

Viewed 463

I'm in the process of integrating with the ASP.NET Feature Management abstraction using a FeatureFilter. One of its constraints is that it registers as a singleton.

This means that in order to access data from my own request-scoped services, I have to be able to resolve them in a fashion similar to how HttpContext can be resolved using HttpContextAccessor.

Are there any known resources or techniques I can follow to set up my own request-scoped services that I want to call in my static-scoped FeatureFilter implementation?

1 Answers

The approach we use is to proxy method calls through a DispatchProxy that will resolve the actual dependency (such as a Typed HTTP Client) from an IServiceProvider and proxy the call to that instance.

The implementation is here: https://github.com/rwkarg/DependencyResolvingProvider

As an example, we have an existing message processor component that implements IHostedService (so a single instance) but if processing a messages requires an HttpClient call, then that client should be resolved per message so that the HttpClientFactory is able to manage the lifetimes of the underlying HttpClient instances.

Related