C# 在ASP.NET MVC应用程序中创建多个单例实例
我有一个ASP.NET MVC 5应用程序,它使用LightInject作为DI容器,我有一个服务类,它位于我的VS解决方案中的另一个类库中C# 在ASP.NET MVC应用程序中创建多个单例实例,c#,asp.net-mvc,caching,singleton,C#,Asp.net Mvc,Caching,Singleton,我有一个ASP.NET MVC 5应用程序,它使用LightInject作为DI容器,我有一个服务类,它位于我的VS解决方案中的另一个类库中 My Solution |____ASP.NET MVC Web App (async controller calls service method) |____Service Class Library |____InMemoryCacheService (Singleton) 此服务类是指以下方法(简化版)创建的InMemoryCach
My Solution
|____ASP.NET MVC Web App (async controller calls service method)
|____Service Class Library
|____InMemoryCacheService (Singleton)
此服务类是指以下方法(简化版)创建的InMemoryCacheService
Singleton I类:
MemoryCacheService中的
是什么?它是如何工作的?是什么让您认为它被多次创建的?上面的代码看起来不错。@DavidG,正如您在Singleton构造函数中看到的,我添加了一条日志消息。当我运行报告两到三次时,我会看到一条消息,说明创建了另一个实例,我可以看到它,因为我的缓存数据是cleared@Backs我在我的原始帖子中添加了我的InMemoryCacheService
类的简化版本。你的MVC应用程序重新启动/回收了吗?
public sealed class InMemoryCacheService
{
private static readonly InMemoryCacheService _singleton = new InMemoryCacheService();
// A private constructor to restrict the object creation from outside
static InMemoryCacheService()
{
}
private InMemoryCacheService()
{
Log.Info("New In Memory Cache Service instance created!");
}
public static InMemoryCacheService Instance
{
get
{
return _singleton;
}
}
public Dictionary<string, ConcurrentDictionary<string, Changeset>> ChangesetCacheDictionary
{
get { return _changesetCacheDictionary; }
set { _changesetCacheDictionary = value; }
}
public string GetChangesetCacheKey(string releaseWorkItemId)
{
return $"{releaseWorkItemId}_{CHANGESET_CACHE}";
}
public T GetOrSet<T>(string cacheKey, TimeSpan duration) where T : class
{
var item = MemoryCache.Default.Get(cacheKey) as T;
if (item == null)
{
lock (CacheLockObject)
{
item = GetItemFromCacheType<T>(cacheKey);
MemoryCache.Default.Add(cacheKey, item, DateTime.Now.Add(duration));
}
}
return item;
}
private T GetItemFromCacheType<T>(string cacheKey) where T : class
{
T result = null;
var tokens = cacheKey.Split('_');
var releaseWorkItemId = tokens[0];
var cacheType = tokens[1];
switch (cacheType)
{
case CHANGESET_CACHE:
result = GetChangesetitItem<T>(releaseWorkItemId);
break;
}
return result;
}
private T GetChangesetitItem<T>(string releaseWorkItemId) where T : class
{
T result = null;
if (ChangesetCacheDictionary == null)
{
ChangesetCacheDictionary = new Dictionary<string, ConcurrentDictionary<string, Changeset>>()
{
{ releaseWorkItemId,new ConcurrentDictionary<string, Changeset>() }
};
}
else if (!ChangesetCacheDictionary.ContainsKey(releaseWorkItemId))
{
ChangesetCacheDictionary.Add(releaseWorkItemId, new ConcurrentDictionary<string, Changeset>());
}
result = ChangesetCacheDictionary[releaseWorkItemId] as T;
return result;
}
GitCommitCache = InMemoryCacheService.Instance.GetOrSet<ConcurrentDictionary<string,GitCommit>>(gitCommitCacheKey,new TimeSpan(1, 0, 0, 0));