public class CacheAttribute : MethodInterceptionAspect
{
public override void OnInvoke(MethodInterceptionArgs methodInterceptionArgs)
{
if ((methodInterceptionArgs.Method.Name == CacheAspectAction.Get.ToString())
//&& (Memory.Cache[cacheKey] != null)
)
{
// methodInterceptionArgs.ReturnValue = HttpRuntime.Cache[cacheKey];
return;
}
object returnVal = methodInterceptionArgs.Invoke(methodInterceptionArgs.Arguments);
ClanCache(cacheKeyBase, cacheKey);
if (returnVal != null)
//Memory.Cache.Insert(cacheKey, returnVal, null, expirationInformation.AbsoluteExpiration, expirationInformation.SlidingExpiration);
methodInterceptionArgs.ReturnValue = returnVal;
}
}
How do I access the in-memory cache in ASP.NET Core from any class, including a PostSharp aspect? For example, I need to access IMemoryCache in MethodInterceptionAspect
and OnMethodBoundaryAspect
.
I'm going to assume here that you're using the built-in ASP.NET Core dependency injection and IMemoryCache implementation. However, the example can be easily adapted to other implementations. And I'm going to choose the Global Service Locator approach for resolving dependencies in the aspect. Below is the modified example from the documentation page.