MVC TwoLevel View Cache
| Ağustos 30, 20171 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // RazorViewEngine Temizleniyor ViewEngines.Engines.Clear(); // Yeni bir RazorViewEngine Ekleniyor. İçeriği dolduruluyor. RazorViewEngine _RazorViewEngine = new RazorViewEngine() { FileExtensions = new string[] { "cshtml" } }; var ViewLocation = new string[] { "~/Views/{1}/{0}.cshtml", "~/Views/Shared/{0}.cshtml", }; _RazorViewEngine.PartialViewLocationFormats = ViewLocation; _RazorViewEngine.MasterLocationFormats = ViewLocation; _RazorViewEngine.ViewLocationFormats = ViewLocation; // TwoLevelViewCache Ekleniyor. _RazorViewEngine.ViewLocationCache = new TwoLevelViewCache(_RazorViewEngine.ViewLocationCache); ViewEngines.Engines.Add(_RazorViewEngine); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | /// <summary> /// By default (when running in Release mode, of course) MVC will cache the results of the lookups in the application cache available via HttpContext.Cache. While this cache works great and helps us avoid having to check for view files on disk there is also a cost associated with using it (this includes the cost of a thread-safe lookup as well as all the additional cache management such as updating entry expiration policies and performance counters). /// To speed things up you could introduce a faster cache in front of the application cache.Fortunately all view engines deriving from VirtualPathProviderViewEngine(that includes WebForms and Razor) have an extensibility point via the settable ViewLocationCache property. /// So we can create a new class that implements the IViewLocationCache interface: /// https://blogs.msdn.microsoft.com/marcinon/2011/08/16/optimizing-asp-net-mvc-view-lookup-performance/ /// </summary> public class TwoLevelViewCache : IViewLocationCache { private readonly static object s_key = new object(); private readonly IViewLocationCache _cache; public TwoLevelViewCache(IViewLocationCache cache) { _cache = cache; } private static IDictionary<string, string> GetRequestCache(HttpContextBase httpContext) { var d = httpContext.Items[s_key] as IDictionary<string, string>; if (d == null) { d = new Dictionary<string, string>(); httpContext.Items[s_key] = d; } return d; } public string GetViewLocation(HttpContextBase httpContext, string key) { var d = GetRequestCache(httpContext); string location; if (!d.TryGetValue(key, out location)) { location = _cache.GetViewLocation(httpContext, key); d[key] = location; } return location; } public void InsertViewLocation(HttpContextBase httpContext, string key, string virtualPath) { _cache.InsertViewLocation(httpContext, key, virtualPath); } } |