Flatwhite.Provider.DefaultCacheKeyProvider.GetCacheKey C# (CSharp) Method

GetCacheKey() public method

Resolve cache key
public GetCacheKey ( _IInvocation invocation, object>.IDictionary invocationContext ) : string
invocation _IInvocation
invocationContext object>.IDictionary
return string
        public virtual string GetCacheKey(_IInvocation invocation, IDictionary<string, object> invocationContext)
        {
            var info = invocationContext.TryGetByKey<ICacheSettings>(Global.__flatwhite_outputcache_attribute);
            if (info == null)
            {
                throw new InvalidOperationException($"{nameof(ICacheSettings)} object not found in {nameof(invocationContext)}");
            }

            // The cache key must be different for different instance of same type
            var key = new StringBuilder($"Flatwhite::{(invocation.Method.DeclaringType ?? invocation.TargetType).FullName}.{invocation.Method.Name}(");
            
            var varyByParams = (info.VaryByParam ?? "").Split(new [] {',',' '}, StringSplitOptions.RemoveEmptyEntries);
            var varyByCustoms = info.GetAllVaryCustomKey().Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);

            var parameters = invocation.Method.GetParameters();
            if (parameters.Length > 0)
            {
                BuildWithParams(invocation, parameters, varyByParams, key);
                key.Remove(key.Length - 2, 2);
            }
            
            key.Append(") :: ");

            if (varyByCustoms.Length > 0)
            {
                foreach (var custom in varyByCustoms)
                {
                    BuildWithCustom("", invocationContext, custom, key);
                    key.Append(", ");
                }
            }
            return key.ToString().TrimEnd(' ', ':', ',');
        }

Usage Example

        public void Should_build_key_from_methodInfo_and_context()
        {
            // Arrange
            var invocation = Substitute.For<_IInvocation>();
            invocation.Arguments.Returns(new object[] {new Guid ("5e31d440-c9f8-4110-b94d-fdf8affdc675") });
            invocation.GetArgumentValue(Arg.Any<int>()).Returns(ct => invocation.Arguments[ct.Arg<int>()]);
            invocation.Method.Returns(typeof(IUserService).GetMethod(nameof(IUserService.GetById), BindingFlags.Instance | BindingFlags.Public));

            var provider = new DefaultCacheKeyProvider();
            var invocationContext = new Dictionary<string, object>();
            invocationContext[Global.__flatwhite_outputcache_attribute] = new OutputCacheAttribute
            {
                VaryByCustom = "query.source, headers.UserAgent, headers.CacheControl.Public, headers.CacheControl.NonExistProperty",
                VaryByParam = "userId"
            };
            invocationContext["query"] = new Dictionary<string, object>
            {
                { "source","a"},
                { "source2","b"},
            };
            var r = new HttpRequestMessage();
            r.Headers.CacheControl = new CacheControlHeaderValue
            {
                Public = true
            };
            r.Headers.Add("User-Agent", "Flatwhite.UnitTest");
            invocationContext["headers"] = r.Headers;

            // Action
            var key = provider.GetCacheKey(invocation, invocationContext);

            // Assert
            Assert.AreEqual("Flatwhite::Flatwhite.Tests.IUserService.GetById(Guid:5e31d440-c9f8-4110-b94d-fdf8affdc675) ::  query.source:a,  headers.UserAgent:Flatwhite.UnitTest,  headers.CacheControl.Public:True, , ", key);
        }