我想在.NET Core 2.0控制台应用程序中使用Microsoft.Extensions.Caching.Memory.MemoryCache(实际上,在一个用于控制台或asp.net应用程序的库中)
我已经创建了一个测试应用:
using System;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
var cache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new Microsoft.Extensions.Caching.Memory.MemoryCacheOptions());
int count = cache.Count;
cache.CreateEntry("item1").Value = 1;
int count2 = cache.Count;
cache.TryGetValue("item1", out object item1);
int count3 = cache.Count;
cache.TryGetValue("item2", out object item2);
int count4 = cache.Count;
Console.WriteLine("Hello World!");
}
}
}
不幸的是,这不起作用。这些项目未添加到缓存中,无法检索它们。
我怀疑我需要使用DependencyInjection,做这样的事情:
using System;
using Microsoft.Extensions.DependencyInjection;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
var provider = new Microsoft.Extensions.DependencyInjection.ServiceCollection()
.AddMemoryCache()
.BuildServiceProvider();
//And now?
var cache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new Microsoft.Extensions.Caching.Memory.MemoryCacheOptions());
var xxx = PSP.Helpers.DependencyInjection.ServiceProvider;
int count = cache.Count;
cache.CreateEntry("item1").Value = 1;
int count2 = cache.Count;
cache.TryGetValue("item1", out object item1);
int count3 = cache.Count;
cache.TryGetValue("item2", out object item2);
int count4 = cache.Count;
Console.WriteLine("Hello World!");
}
}
}
不幸的是,这也没有用,我怀疑我不应该创建一个新的内存缓存,而是从服务提供商那里获得它,但是还没有能够做到这一点。
有什么想法吗?
答案 0 :(得分:9)
配置提供程序后,通过GetService
扩展方法
var provider = new ServiceCollection()
.AddMemoryCache()
.BuildServiceProvider();
//And now?
var cache = provider.GetService<IMemoryCache>();
//...other code removed for brevity;
来自评论:
不需要使用依赖注入,唯一需要的是处理CreateEntry()的返回值。
CreateEntry
返回的条目需要处理。上 dispose,它被添加到缓存中:
using (var entry = cache.CreateEntry("item2")) {
entry.Value = 2;
entry.AbsoluteExpiration = DateTime.UtcNow.AddDays(1);
}
答案 1 :(得分:2)
这是.NET Core中完整的控制台应用程序代码
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Primitives;
using System;
using System.Threading;
namespace InMemoryNetCore
{
class Program
{
static void Main(string[] args)
{
IMemoryCache cache = new MemoryCache(new MemoryCacheOptions());
object result;
string key = "KeyName";
// Create / Overwrite
result = cache.Set(key, "Testing 1");
result = cache.Set(key, "Update 1");
// Retrieve, null if not found
result = cache.Get(key);
Console.WriteLine("Output of KeyName Value="+result);
// Check if Exists
bool found = cache.TryGetValue(key, out result);
Console.WriteLine("KeyName Found=" + result);
// Delete item
cache.Remove(key);
//set item with token expiration and callback
TimeSpan expirationMinutes = System.TimeSpan.FromSeconds(0.1);
var expirationTime = DateTime.Now.Add(expirationMinutes);
var expirationToken = new CancellationChangeToken(
new CancellationTokenSource(TimeSpan.FromMinutes(0.001)).Token);
// Create cache item which executes call back function
var cacheEntryOptions = new MemoryCacheEntryOptions()
// Pin to cache.
.SetPriority(Microsoft.Extensions.Caching.Memory.CacheItemPriority.Normal)
// Set the actual expiration time
.SetAbsoluteExpiration(expirationTime)
// Force eviction to run
.AddExpirationToken(expirationToken)
// Add eviction callback
.RegisterPostEvictionCallback(callback: CacheItemRemoved);
//add cache Item with options of callback
result = cache.Set(key,"Call back cache Item", cacheEntryOptions);
Console.WriteLine(result);
Console.ReadKey();
}
private static void CacheItemRemoved(object key, object value, EvictionReason reason, object state)
{
Console.WriteLine(key + " " + value + " removed from cache due to:" + reason);
}
}
}
来源:In Memory cache C# (Explanation with example in .NET and .NET Core)
答案 2 :(得分:1)
IMemoryCache cache = new MemoryCache(new MemoryCacheOptions());
object result = cache.Set("Key", new object());
bool found = cache.TryGetValue("Key", out result);
在GitHub上查看完整的Memory Cache Sample。
您需要在项目中添加NuGet Microsoft.Extensions.Caching.Memory包才能使用MemoryCache
答案 3 :(得分:0)
对于上面的回答,我想为常见的缓存操作添加一些简洁的替代方法:
using Microsoft.Extensions.Caching.Memory;
// ... (further down) ...
MemoryCache cache = new MemoryCache(new MemoryCacheOptions() );
// get a value from the cache
// both are equivalent
// obviously, replace "string" with the correct type
string value = (string)cache.Get("mykey");
string value = cache.Get<string>("mykey");
// setting values in the cache
// no expiration time
cache.Set("mykey", myVar);
// absolute expiration numMinutes from now
cache.Set("mykey", myVar, DateTimeOffset.Now.AddMinutes(numMinutes));
// sliding expiration numMinutes from now
// "sliding expiration" means that if it's accessed within the time period,
// the expiration is extended
MemoryCacheEntryOptions options = new MemoryCacheEntryOptions();
options.SetSlidingExpiration(TimeSpan.FromMinutes(numMinutes));
webcache.Set("mykey", myVar, options);
// or, if you want to do it all in one statement:
webcache.Set("mykey", myVar,
new MemoryCacheEntryOptions {SlidingExpiration = TimeSpan.FromMinutes(numMinutes)});