简体   繁体   中英

PostSharp Caching MethodInterceptionAspect using ASP.NET Core in-memory cache

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.

// A helper class that resolves services using built-in ASP.NET Core service provider.
public static class AspectServiceLocator
{
    private static IServiceProvider serviceProvider;

    public static void Initialize(IWebHost host)
    {
        serviceProvider = host.Services;
    }

    public static Lazy<T> GetService<T>() where T : class
    {
        return new Lazy<T>(GetServiceImpl<T>);
    }

    private static T GetServiceImpl<T>()
    {
        if (serviceProvider == null)
            throw new InvalidOperationException();

        return (T) serviceProvider.GetService(typeof(T));
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        IWebHost host = CreateWebHostBuilder(args).Build();

        // Initialize the AspectServiceLocator during ASP.NET Core program start-up
        AspectServiceLocator.Initialize(host);

        host.Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

[PSerializable]
public class CacheAttribute : MethodInterceptionAspect
{
    private static Lazy<IMemoryCache> cache;

    static CacheAttribute()
    {
        // Use AspectServiceLocator to initialize the cache service field at application run-time.
        if (!PostSharpEnvironment.IsPostSharpRunning)
        {
            cache = AspectServiceLocator.GetService<IMemoryCache>();
        }
    }

    public override void OnInvoke(MethodInterceptionArgs args)
    {
        object cacheKey = args.Method.Name;
        object cachedResult;

        if (cache.Value.TryGetValue(cacheKey, out cachedResult))
        {
            args.ReturnValue = cachedResult;
            return;
        }

        args.Proceed();

        cache.Value.Set(cacheKey, args.ReturnValue);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM