gpt4 book ai didi

c# - 如何在 C# Core 控制台应用程序中使用 MemoryCache?

转载 作者:太空狗 更新时间:2023-10-29 19:54:40 25 4
gpt4 key购买 nike

我想在 .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!");
}
}
}

不幸的是,这也不起作用,我怀疑我不应该创建一个新的内存缓存,而是从服务提供商那里获取它,但一直无法做到这一点。

有什么想法吗?

最佳答案

配置提供程序后,通过GetService 扩展方法检索缓存

var provider = new ServiceCollection()
.AddMemoryCache()
.BuildServiceProvider();

//And now?
var cache = provider.GetService<IMemoryCache>();

//...other code removed for brevity;

来自评论:

It's not needed to use dependency injection, the only thing needed was disposing the return value of CreateEntry(). The entry returned by CreateEntry needs to be disposed. On dispose, it is added to the cache:

using (var entry = cache.CreateEntry("item2")) { 
entry.Value = 2;
entry.AbsoluteExpiration = DateTime.UtcNow.AddDays(1);
}

关于c# - 如何在 C# Core 控制台应用程序中使用 MemoryCache?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45751948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com