I would like to cache date from one table, and return it when user do request to this table. I created class like this:
public interface ICategoryCache
{
IEnumerable<Category> GetCategories();
}
public class CategoryCache : ICategoryCache
{
private IEnumerable<Category> _categories;
public CategoryCache(ItBuildsDbContext context)
{
_categories = context.Category.ToList();
}
public IEnumerable<Category> GetCategories()
{
return _categories;
}
}
I wanted to add dependency injection as Singleton, but class which have to use this object is Scoped (and it throw error: Cannot consume scoped service). How should I do it properly? I am not able to change Scoped class to Singleton.
Should I for example create Factory which will create my Singleton object CategoryCache?
My solution for this problem which work:
public class CategoryCache
{
private readonly IEnumerable<Category> _categories;
private static CategoryCache? _categoryCache;
private CategoryCache(ItBuildsDbContext context)
{
_categories = context.Category.ToList();
}
public static CategoryCache Create(ItBuildsDbContext context)
{
if(_categoryCache == null)
{
_categoryCache = new CategoryCache(context);
}
return _categoryCache;
}
public IEnumerable<Category> GetCategories()
{
return _categories!;
}
}
public interface IFactoryCategoryCache
{
CategoryCache Create();
}
public class FactoryCategoryCache : IFactoryCategoryCache
{
private readonly ItBuildsDbContext _context;
public FactoryCategoryCache(ItBuildsDbContext context)
{
_context = context;
}
public CategoryCache Create()
{
return CategoryCache.Create(_context);
}
}
service.AddScoped<IFactoryCategoryCache, FactoryCategoryCache>();
But is there a better solution here?

