C
C#5d ago
Tristen

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
Pobiega
Pobiega5d ago
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();
Tristen
TristenOP5d ago
I just stumbled upon this, will it work?
//DI file
services.AddKeyedScoped<IPlatformRepository, SqlitePlatformRepository>("inner");
services.AddSingleton<IPlatformRepository, CachedPlatformRepository>();

//services
private readonly IPlatformRepository _platform;
public Service(IPlatformRepository platform)
{
_platform = platform;
}

//CachedPlatformRepository
var repository = scope.ServiceProvider.GetRequiredKeyedService<IPlatformRepository>("inner");
//DI file
services.AddKeyedScoped<IPlatformRepository, SqlitePlatformRepository>("inner");
services.AddSingleton<IPlatformRepository, CachedPlatformRepository>();

//services
private readonly IPlatformRepository _platform;
public Service(IPlatformRepository platform)
{
_platform = platform;
}

//CachedPlatformRepository
var repository = scope.ServiceProvider.GetRequiredKeyedService<IPlatformRepository>("inner");
Pobiega
Pobiega5d ago
something like that yeah
Cracker
Cracker4d ago
@Pobiega let's say scoped service serves like httpcontext info. In that case scopeFactory instance will be empty right? Same applies for serviceProvider
Pobiega
Pobiega4d ago
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

Did you find this page helpful?