Cache vs Persistence Repository and DI
anyone have recommendations, for a asp.net backend, a decent way to cache db results and make available to services? I was trying to register the cache as a singleton and the persistence repository as scoped, but I haven't fingered out an elegant way to do it. I figure this problem must have been solved a long time ago.
I was thinking, services should NOT care if its CacheRepository or SqlServerRepository or PostgresRepository as long as it is IRepository, but I couldn't figure out how to make Cache IRepository as a singleton periodically refreshing from Postgres IRepository as a scoped
5 Replies
if you have something
Singleton
that needs to access something Scoped
, you need a IServiceScopeFactory
you can inject that into the singleton service, and from that call CreateScope
which gives you a scope, from which you can resolve the scoped service. Remember to dispose the scope when you are done with it
normally via using var scope = _scopeFactory.CreateScope();
I just stumbled upon this, will it work?
something like that yeah
@Pobiega let's say scoped service serves like httpcontext info. In that case scopeFactory instance will be empty right?
Same applies for serviceProvider
HttpContext is special, its created and inserted into the scope by ASP.NET itself, and thus only for the scope that ASP.NET owns
Don't understand what you mean by "same applies for service provider" - the SP itself isnt scoped and can be injected anywhere