Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 690
Alexander Trauzzi Avatar asked Nov 07 '22 02:11

Alexander Trauzzi


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.

like image 169
Ryan Karg Avatar answered Nov 17 '22 12:11

Ryan Karg