本文整理汇总了C#中ICache.Get方法的典型用法代码示例。如果您正苦于以下问题:C# ICache.Get方法的具体用法?C# ICache.Get怎么用?C# ICache.Get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ICache
的用法示例。
在下文中一共展示了ICache.Get方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetMethodReturnsCachedObject
private static void GetMethodReturnsCachedObject(ICache<object> cache)
{
var o = new object();
var i = cache.Cache(o);
Assert.IsTrue(cache.Get(i).Equals(o));
}
示例2: fetch
public async Task<JToken> fetch(string url, ILogger logger, ICache cache)
{
JToken fromCache = cache.Get (url);
if (fromCache != null) {
return await Task.FromResult(fromCache);
} else {
return await _fetch (url, logger, cache);
}
}
示例3: PropertyService
public PropertyService(ICache<Dictionary<string, object>> cache, IPropertyRepository propertyRepository)
{
_cache = cache;
_propertyRepository = propertyRepository;
_propertyDictionary = _cache.Get(_key);
if (_propertyDictionary == null)
{
InitializeCache();
}
}
示例4: PostSharpProjectCompiler
public PostSharpProjectCompiler(
ICache cache,
ICacheContextAccessor cacheContextAccessor,
INamedCacheDependencyProvider namedCacheProvider,
IAssemblyLoadContext loadContext,
IApplicationEnvironment environment,
IServiceProvider services)
{
_services = services;
_compiler = new RoslynCompiler(
cache,
cacheContextAccessor,
namedCacheProvider,
loadContext,
environment,
services);
_cache = cache;
_workingDirectory = cache.Get<string>("PostSharp.Dnx.WorkingDirectory", cacheContext => Path.Combine(Path.GetTempPath(), "PostSharp.Dnx", Guid.NewGuid().ToString()));
Task.Run(() => PurgeWorkingDirectories());
CreateWorkingDirectory();
}
示例5: ExecuteGetOrDeleteAsync
private WebQueryAsyncResult ExecuteGetOrDeleteAsync(ICache cache,
string key,
string url,
WebRequest request,
object userState)
{
var fetch = cache.Get<Stream>(key);
if (fetch != null)
{
var args = new WebQueryResponseEventArgs(fetch);
OnQueryResponse(args);
var result = new WebQueryAsyncResult
{
CompletedSynchronously = true
};
return result;
}
else
{
var state = new Triplet<WebRequest, Pair<ICache, string>, object>
{
First = request,
Second = new Pair<ICache, string>
{
First = cache,
Second = key
},
Third = userState
};
var args = new WebQueryRequestEventArgs(url);
OnQueryRequest(args);
var inner = request.BeginGetResponse(GetAsyncResponseCallback, state);
RegisterAbortTimer(request, inner);
var result = new WebQueryAsyncResult { InnerResult = inner };
return result;
}
}
示例6: RoslynCompiler
public RoslynCompiler(ICache cache,
ICacheContextAccessor cacheContextAccessor,
INamedCacheDependencyProvider namedDependencyProvider,
IAssemblyLoadContext loadContext,
IApplicationEnvironment environment,
IServiceProvider services)
{
_cache = cache;
_cacheContextAccessor = cacheContextAccessor;
_namedDependencyProvider = namedDependencyProvider;
_loadContext = loadContext;
_environment = environment;
_services = services;
_assemblyMetadataFactory = fileReference =>
{
return _cache.Get<AssemblyMetadata>(fileReference.Path, ctx =>
{
ctx.Monitor(new FileWriteTimeCacheDependency(fileReference.Path));
return fileReference.CreateAssemblyMetadata();
});
};
}
示例7: ExpandEmbeddedReferences
private static void ExpandEmbeddedReferences(ICache cache, IList<IMetadataReference> references)
{
var otherReferences = new List<IMetadataReference>();
foreach (var reference in references)
{
var fileReference = reference as IMetadataFileReference;
if (fileReference != null &&
string.Equals(Path.GetExtension(fileReference.Path), ".dll", StringComparison.OrdinalIgnoreCase))
{
// We don't use the exact path since that might clash with another key
var key = "ANI_" + fileReference.Path;
var embeddedRefs = cache.Get<IList<IMetadataEmbeddedReference>>(key, ctx =>
{
ctx.Monitor(new FileWriteTimeCacheDependency(fileReference.Path));
using (var fileStream = File.OpenRead(fileReference.Path))
using (var reader = new PEReader(fileStream))
{
return reader.GetEmbeddedReferences();
}
});
otherReferences.AddRange(embeddedRefs);
}
}
references.AddRange(otherReferences);
}
示例8: GetMethodReturnsNullAfterFeedObject
private static void GetMethodReturnsNullAfterFeedObject(ICache<object> cache)
{
var o = new object();
var i = cache.Cache(o);
cache.Free(i);
Assert.IsNull(cache.Get(i));
}
示例9: HandleResponse
public ResponseHandlerResult HandleResponse(HttpRequestBase httpRequest, HttpResponseBase httpResponse, IResponse suggestedResponse, ICache cache, string cacheKey)
{
httpRequest.ThrowIfNull("request");
httpResponse.ThrowIfNull("httpResponse");
suggestedResponse.ThrowIfNull("suggestedResponse");
if (!suggestedResponse.CachePolicy.HasPolicy || cache == null || cacheKey == null)
{
return ResponseHandlerResult.ResponseNotHandled();
}
CacheItem cacheItem = cache.Get(cacheKey);
string responseETag = suggestedResponse.CachePolicy.ETag;
#region If-Match precondition header
IfMatchHeader[] ifMatchHeaders = IfMatchHeader.ParseMany(httpRequest.Headers["If-Match"]).ToArray();
// Only consider If-Match headers if response status code is 2xx or 412
if (ifMatchHeaders.Any() && ((suggestedResponse.StatusCode.StatusCode >= 200 && suggestedResponse.StatusCode.StatusCode <= 299) || suggestedResponse.StatusCode.StatusCode == 412))
{
// Return 412 if no If-Match header matches the response ETag
// Return 412 if an "If-Match: *" header is present and the response has no ETag
if (ifMatchHeaders.All(arg => arg.EntityTag.Value != responseETag) ||
(responseETag == null && ifMatchHeaders.Any(arg => arg.EntityTag.Value == "*")))
{
return WriteResponse(httpResponse, Response.PreconditionFailed());
}
}
#endregion
#region If-None-Match precondition header
IfNoneMatchHeader[] ifNoneMatchHeaders = IfNoneMatchHeader.ParseMany(httpRequest.Headers["If-None-Match"]).ToArray();
if (ifNoneMatchHeaders.Any())
{
// Return 304 if an If-None-Match header matches the response ETag and the request method was GET or HEAD
// Return 304 if an "If-None-Match: *" header is present, the response has an ETag and the request method was GET or HEAD
// Return 412 if an "If-None-Match: *" header is present, the response has an ETag and the request method was not GET or HEAD
if (ifNoneMatchHeaders.Any(arg => arg.EntityTag.Value == responseETag) ||
(ifNoneMatchHeaders.Any(arg => arg.EntityTag.Value == "*") && responseETag != null))
{
if (String.Equals(httpRequest.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase) || String.Equals(httpRequest.HttpMethod, "HEAD", StringComparison.OrdinalIgnoreCase))
{
if (cacheItem != null)
{
cacheItem.Response.CachePolicy.Apply(httpResponse.Cache);
}
else
{
suggestedResponse.CachePolicy.Apply(httpResponse.Cache);
}
return WriteResponse(httpResponse, Response.NotModified());
}
return WriteResponse(httpResponse, Response.PreconditionFailed());
}
}
#endregion
#region If-Modified-Since precondition header
IfModifiedSinceHeader ifModifiedSinceHeader = IfModifiedSinceHeader.Parse(httpRequest.Headers["If-Modified-Since"]);
bool validIfModifiedSinceHttpDate = ifModifiedSinceHeader != null && ifModifiedSinceHeader.HttpDate <= _systemClock.UtcDateTime;
// Only consider an If-Modified-Since header if response status code is 200 and the HTTP-date is valid
if (suggestedResponse.StatusCode.ParsedStatusCode == HttpStatusCode.OK && validIfModifiedSinceHttpDate)
{
// Return 304 if the response was cached before the HTTP-date
if (cacheItem != null && cacheItem.CachedUtcTimestamp < ifModifiedSinceHeader.HttpDate)
{
return WriteResponse(httpResponse, Response.NotModified());
}
}
#endregion
#region If-Unmodified-Since precondition header
IfUnmodifiedSinceHeader ifUnmodifiedSinceHeader = IfUnmodifiedSinceHeader.Parse(httpRequest.Headers["If-Unmodified-Since"]);
bool validIfUnmodifiedSinceHttpDate = ifUnmodifiedSinceHeader != null && ifUnmodifiedSinceHeader.HttpDate <= _systemClock.UtcDateTime;
// Only consider an If-Unmodified-Since header if response status code is 2xx or 412 and the HTTP-date is valid
if (((suggestedResponse.StatusCode.StatusCode >= 200 && suggestedResponse.StatusCode.StatusCode <= 299) || suggestedResponse.StatusCode.StatusCode == 412) && validIfUnmodifiedSinceHttpDate)
{
// Return 412 if the previous response was removed from the cache or was cached again at a later time
if (cacheItem == null || cacheItem.CachedUtcTimestamp >= ifUnmodifiedSinceHeader.HttpDate)
{
return WriteResponse(httpResponse, Response.PreconditionFailed());
}
}
#endregion
#region No server caching
//.........这里部分代码省略.........
示例10: Get
/**
* Entry point to get an {@link Api} object.
* Example: <code>API api = API.get("https://lesbonneschoses.prismic.io/api", null, new Cache.BuiltInCache(999), new Logger.PrintlnLogger());</code>
*
* @param endpoint the endpoint of your prismic.io content repository, typically https://yourrepoid.prismic.io/api
* @param accessToken Your Oauth access token if you wish to use one (to access future content releases, for instance)
* @param cache instance of a class that implements the {@link Cache} interface, and will handle the cache
* @param logger instance of a class that implements the {@link Logger} interface, and will handle the logging
* @return the usable API object
*/
public static async Task<Api> Get(String endpoint, String accessToken, ICache cache, ILogger logger, HttpClient client) {
String url = (accessToken == null ? endpoint : (endpoint + "?access_token=" + HttpUtility.UrlEncode(accessToken)));
PrismicHttpClient prismicHttpClient = new PrismicHttpClient(client);
JToken json = cache.Get(url);
if (json == null)
{
json = await prismicHttpClient.fetch(url, logger, cache);
cache.Set(url, 5000L, json);
}
ApiData apiData = ApiData.Parse(json);
return new Api(apiData, accessToken, cache, logger, prismicHttpClient);
}
示例11: OnActionExecuting
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
// read configuration settings
cache_enabled = ConfigurationManager.AppSettings["cache_enabled"].ToString() == "true";
// check custom attributes - if any
cache_attribute = (CacheAttribute)filterContext.ActionDescriptor.GetCustomAttributes(typeof(CacheAttribute), false).FirstOrDefault();
omit_database = filterContext.ActionDescriptor.GetCustomAttributes(typeof(OmitDatabaseAttribute), false).FirstOrDefault() != null;
// if the attribute cache is present and the cache is enabled in the parameter in the web.config file
if (cache_enabled && cache_attribute != null)
{
cache_ID = filterContext.ActionDescriptor.ActionName + "_" + string.Join("_", filterContext.ActionParameters.Values);
cache = new MongoCache();
String cached = cache.Get(cache_ID);
// if the item is already in the "cache"
if (cached != null)
{
var result = new ContentResult();
result.ContentType = "application/json";
result.Content = cached;
filterContext.Result = result;
return;
}
}
// initiate the database only if it is needed
if (!omit_database)
{
database = new Database(ConfigurationManager.AppSettings["connectionString"].ToString());
}
base.OnActionExecuting(filterContext);
}