PostSharp缓存方法InterceptionAspect使用ASP.NET Core内存缓存

时间:2018-08-27 12:58:14

标签: c# .net-core postsharp

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;
    }
}

如何从任何类(包括PostSharp方面)访问ASP.NET Core中的内存缓存?例如,我需要访问MethodInterceptionAspectOnMethodBoundaryAspect中的IMemoryCache

1 个答案:

答案 0 :(得分:1)

在这里,我假设您正在使用内置的ASP.NET Core依赖项注入和IMemoryCache实现。然而,该示例可以容易地适应于其他实施方式。我将选择Global Service Locator方法来解决方面的依赖性。下面是文档页面中的修改示例。

// 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);
    }
}