I am building a online shop website. I want to display ProductCategory as a Sidebar (short list categories, Eg Clothes, Electronics, Furniture, Books, etc).
At the end, I want to send around productcategory _cache variable to all controllers.Does this methodology seem correct? Additionally, how do I remove unnecessary memorycache parameter in Home Controller? Make a method in Scheduled stuff to retrieve it?
DI Solution:
public class HomeController : Controller
{
private readonly IMemoryCache _cache;
public IScheduledStuff _scheduledstuff;
public HomeController(IMemoryCache cache, IScheduledStuff scheduledstuff)
{
_cache = cache;
_scheduledstuff = scheduledstuff;
_scheduledstuff.ScheduleItemsExecute();
}
public IActionResult Index()
{
ViewBag.ProductCategoryList = _cache.Get<IEnumerable<ProductCategory>>("Teststore");
return View();
}
}
public class ProductCategoryRepository : IProductCategoryRepository<ProductCategory>
{
public IEnumerable<ProductCategory> GetAllProductCategory()
{
return _context.ProductCategory.ToList();
}
}
public ProductCategory()
{
public int ProductCategoryId { get; set; }
public string ProductCategoryName { get; set; }
public string ProductCategoryDescription { get; set; }
}
public class ScheduledStuff : IScheduledStuff
{
private readonly DatabaseContext _context;
IMemoryCache MemCache;
public IProductCategoryRepository<ProductCategory> productcategoryrepository;
public ScheduledStuff(DatabaseContext context, IMemoryCache memCache)
{
_context = context;
MemCache = memCache;
productcategoryrepository = new ProductCategoryRepository(_context);
}
public void ScheduleItemsExecute()
{
var testdata = productcategoryrepository.GetAllProductCategory();
MemCache.Set("Teststore", testdata);
}
}
public class Startup
{
public IProductCategoryRepository<ProductCategory> productcategoryrepository;
public IMemoryCache memorycache;
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
services.AddSingleton<ScheduledStuff>();
Asp.Net Core: Use memory cache outside controller
Solution Static: Keep receiving Null exception error, can someone help fix this?
public static class MemoryCacheStatic
{
public static IMemoryCache MemCacheStatic;
public static IProductCategoryRepository<ProductCategory> productcategoryrepositorystatic;
// Error on this line: <--- NullReferenceException: Object reference not set to an instance of an object.
public static IEnumerable<ProductCategory> ProductCategoryStatic = productcategoryrepositorystatic.GetAllProductCategory();
public static void SetValues()
{
ProductCategoryStatic = productcategoryrepositorystatic.GetAllProductCategory();
MemCacheStatic.Set("Teststore", ProductCategoryStatic) ;
}