gpt4 book ai didi

c# - PostSharp 缓存 MethodInterceptionAspect 使用 ASP.NET Core 内存缓存

转载 作者:行者123 更新时间:2023-11-30 22:59:40 25 4
gpt4 key购买 nike

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 中的内存缓存?例如,我需要访问 IMemoryCacheMethodInterceptionAspectOnMethodBoundaryAspect 中。

最佳答案

我在这里假设您正在使用内置的 ASP.NET Core 依赖项注入(inject)和 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);
}
}

关于c# - PostSharp 缓存 MethodInterceptionAspect 使用 ASP.NET Core 内存缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52039937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com