title: ASP.NET Core Custom Authorization & Memory Cache
body: <p>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.</p>
  <p>This is CacheHelperClass</p>
  <pre><code>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&lt;List&lt;RoleTreeListViewModel&gt;&gt; GetRoleTreeListViewModel()
      {
          var cacheList = memCache.Get&lt;List&lt;RoleTreeListViewModel&gt;&gt;(&quot;RolTree&quot;);
          if (cacheList == null)
          {
              var model_list_result =
                  await new RoleTreeRepository(configuration).GetAllRoleTreeForAuthorization();
              cacheList = model_list_result;
              memCache.Set(&quot;RolTree&quot;, model_list_result);
          }
          return cacheList;
      }
  </code></pre>
  <p>This is ICacheHelper class</p>
  <pre><code> public interface ICacheHelper
  {
      public Task&lt;List&lt;RoleTreeListViewModel&gt;&gt; GetRoleTreeListViewModel();
  </code></pre>
  <p>Now, CustomAuthorize where I stuck.</p>
  <pre><code> public class CustomAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
  {
      private  ICacheHelper cacheHelper;        
      public void OnAuthorization(AuthorizationFilterContext authorizationFilterContext)
      {
          cacheHelper = new CacheHelper()//I cannot call it here
  
  
          cacheHelper.GetRoleTreeListViewModel();
          Task&lt;List&lt;RoleTreeListViewModel&gt;&gt; oParentRoleTreeList =  cacheHelper.GetRoleTreeListViewModel();
          Task&lt;List&lt;Item&gt;&gt; oParentItemList =  cacheHelper.GetItemList();
          Task&lt;List&lt;Role_ItemListViewModel&gt;&gt; oParentRoleItemList =  cacheHelper.GetRole_ItemList();
          string filePath = authorizationFilterContext.HttpContext.Request.Path;
          string hataSayfasi = &quot;~/Account/Login?returnUrl=&quot; + filePath;
          string queryString = string.Empty;
          var request = authorizationFilterContext.HttpContext.Request;
  </code></pre>
  <p>Startup.cs;</p>
  <pre><code>  public void ConfigureServices(IServiceCollection services)
      {
  
          services.AddTransient&lt;ICacheHelper, CacheHelper&gt;();
          services.AddMemoryCache();
  </code></pre>