I am implementing a program that Caches all Roles by combining them with CustomAuthorize. It is a page-based authorization. In the customAuthorize Class I couldn't figure out how to access CacheHelper.cs via ICacheHelper.
This is CacheHelperClass
public class CacheHelper : ICacheHelper
{
private readonly IMemoryCache memCache;
private readonly IConfiguration configuration;
public CacheHelper(IServiceProvider serviceProvider, IConfiguration configuration)
{
this.memCache = (IMemoryCache)serviceProvider.GetService(typeof(IMemoryCache));
this.configuration = configuration;
}
public async Task<List<RoleTreeListViewModel>> GetRoleTreeListViewModel()
{
var cacheList = memCache.Get<List<RoleTreeListViewModel>>("RolTree");
if (cacheList == null)
{
var model_list_result =
await new RoleTreeRepository(configuration).GetAllRoleTreeForAuthorization();
cacheList = model_list_result;
memCache.Set("RolTree", model_list_result);
}
return cacheList;
}
This is ICacheHelper class
public interface ICacheHelper
{
public Task<List<RoleTreeListViewModel>> GetRoleTreeListViewModel();
Now, CustomAuthorize where I stuck.
public class CustomAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
private ICacheHelper cacheHelper;
public void OnAuthorization(AuthorizationFilterContext authorizationFilterContext)
{
cacheHelper = new CacheHelper()//I cannot call it here
cacheHelper.GetRoleTreeListViewModel();
Task<List<RoleTreeListViewModel>> oParentRoleTreeList = cacheHelper.GetRoleTreeListViewModel();
Task<List<Item>> oParentItemList = cacheHelper.GetItemList();
Task<List<Role_ItemListViewModel>> oParentRoleItemList = cacheHelper.GetRole_ItemList();
string filePath = authorizationFilterContext.HttpContext.Request.Path;
string hataSayfasi = "~/Account/Login?returnUrl=" + filePath;
string queryString = string.Empty;
var request = authorizationFilterContext.HttpContext.Request;
Startup.cs;
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<ICacheHelper, CacheHelper>();
services.AddMemoryCache();
var cacheHelper = authorizationFilterContext.HttpContext.RequestServices.GetService(typeof(ICacheHelper)) as ICacheHelper