在C#中使用SpatialFocus.MethodCache实现静态方法缓存遇报错求助
解决SpatialFocus.MethodCache静态方法缓存的MSBUILD警告问题
你遇到的警告是因为Fody织入器无法访问到你定义的protected静态缓存属性,同时该属性未完成初始化。SpatialFocus.MethodCache支持静态方法缓存,只需调整以下两点即可解决:
1. 调整缓存属性的访问修饰符并初始化
将IMemoryCache静态属性改为public(确保织入器能访问),同时初始化MemoryCache实例:
using Microsoft.Extensions.Caching.Memory; using SpatialFocus.MethodCache; public class Test { // 改为public静态属性,并完成初始化 public static IMemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); [Cache] public static string TestMethod() { return "hello"; } }
2. 依赖注入场景下的静态属性赋值(可选)
如果是在ASP.NET Core等依赖注入环境中,不要直接初始化MemoryCache,而是从DI容器中获取实例并赋值给静态属性:
// Program.cs 中 var builder = WebApplication.CreateBuilder(args); builder.Services.AddMemoryCache(); var app = builder.Build(); // 从容器获取IMemoryCache实例并赋值给静态属性 Test.MemoryCache = app.Services.GetRequiredService<IMemoryCache>(); app.Run();
这样修改后,Fody织入器就能正确识别到静态的缓存容器,为静态方法生成缓存逻辑,警告也会消失。
内容的提问来源于stack exchange,提问作者Eugene
相关产品推荐
相关产品推荐

