gpt4 book ai didi

caching - 有没有办法在 Microsoft Enterprise Library 中以编程方式创建多个 CacheManager 实例而不依赖于配置文件

转载 作者:行者123 更新时间:2023-12-05 00:02:59 26 4
gpt4 key购买 nike

我们正在尝试迁移以使用 Microsoft Enterprise Library - 缓存块。然而,缓存管理器初始化似乎与配置文件条目紧密相关,我们的应用程序会动态创建内存中的“容器”。无论如何,是否可以使用预先配置的值集(仅限内存)动态实例化缓存管理器的实例。

最佳答案

Enterprise Library 5 有一个 fluent configuration这使得以编程方式配置块变得容易。例如:

var builder = new ConfigurationSourceBuilder();

builder.ConfigureCaching()
.ForCacheManagerNamed("MyCache")
.WithOptions
.UseAsDefaultCache()
.StoreInIsolatedStorage("MyStore")
.EncryptUsing.SymmetricEncryptionProviderNamed("MySymmetric");

var configSource = new DictionaryConfigurationSource();
builder.UpdateConfigurationWithReplace(configSource);
EnterpriseLibraryContainer.Current
= EnterpriseLibraryContainer.CreateDefaultContainer(configSource);

不幸的是,您似乎需要一次配置整个块,这样您就无法即时添加 CacheManager。 (当我在同一个构建器上两次调用 ConfigureCaching() 时会抛出异常。)您可以创建一个新的 ConfigurationSource但随后您会丢失以前的配置。也许有一种方法可以检索现有配置,修改它(例如添加一个新的 CacheManager )然后替换它?我一直找不到办法。

另一种方法是使用 Caching直接上课。

以下示例使用 Caching类来实例化两个 CacheManager实例并将它们存储在静态 Dictionary 中.不需要配置,因为它不使用容器。我不确定这是个好主意——我觉得有点不对劲。这是非常基本的,但希望有所帮助。

public static Dictionary<string, CacheManager> caches = new Dictionary<string, CacheManager>();

static void Main(string[] args)
{
IBackingStore backingStore = new NullBackingStore();
ICachingInstrumentationProvider instrProv = new CachingInstrumentationProvider("myInstance", false, false,
new NoPrefixNameFormatter());

Cache cache = new Cache(backingStore, instrProv);
BackgroundScheduler bgScheduler = new BackgroundScheduler(new ExpirationTask(null, instrProv), new ScavengerTask(0,
int.MaxValue, new NullCacheOperation(), instrProv), instrProv);

CacheManager cacheManager = new CacheManager(cache, bgScheduler, new ExpirationPollTimer(int.MaxValue));
cacheManager.Add("test1", "value1");
caches.Add("cache1", cacheManager);

cacheManager = new CacheManager(new Cache(backingStore, instrProv), bgScheduler, new ExpirationPollTimer(int.MaxValue));
cacheManager.Add("test2", "value2");
caches.Add("cache2", cacheManager);

Console.WriteLine(caches["cache1"].GetData("test1"));
Console.WriteLine(caches["cache2"].GetData("test2"));
}

public class NullCacheOperation : ICacheOperations
{
public int Count { get { return 0; } }
public Hashtable CurrentCacheState { get { return new System.Collections.Hashtable(); } }
public void RemoveItemFromCache(string key, CacheItemRemovedReason removalReason) {}
}

如果过期和清理策略相同,也许最好创建一个 CacheManager然后用一些智能的键名来代表不同的“容器”。例如。键名的格式可以是“{container name}:{item key}”(假设冒号不会出现在容器或键名中)。

关于caching - 有没有办法在 Microsoft Enterprise Library 中以编程方式创建多个 CacheManager 实例而不依赖于配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7413043/

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