函数)
C#
// Container Names
private const string ReferenceDataCacheContainer = "Reference";
private const string ActivityCacheContainer = "Activity";
private const string SearchQueryCacheContainer = "ActivitySearch";
private readonly ICachingProvider cacheProvider;
private readonly IActivitiesRepository activitiesRepository;
public CachedActivitiesRepository() :
this (new VelocityProvider(), new ActivitiesRepository())
{
}
public CachedActivitiesRepository(ICachingProvider cacheProvider, IActivitiesRepository activitiesRepository)
{
this.cacheProvider = cacheProvider;
this.activitiesRepository = activitiesRepository;
}
注意:CachedActivitiesRepository 包含您在任务 1 中创建的已命名缓存的名称。
此外,它 还有一个缓存提供程序和活动存储库。首先定义存储库装饰器将使用的缓存实例,其次在数据未存储在缓 存中时在其中获取数据的实际存储库。
在调用默认构造函数时,它将创建 VelocityProvider 和 ActivitiesRepository 的实例。随后,调用另外一个构造函数,使用已经创建的实例作为参数。
5.实现 RetrieveStates 方法。为此,复制 CachedActivitiesRepository.cs 类中的以下代码:
(代码片段 – 增强 PlanMyNight MVC 应用程序– CachedActivitiesRepository RetrieveStates)
C#
public IEnumerable<string> RetrieveStates()
{
var cacheKey = "states";
// retrieve states from Cache
IEnumerable<string> data = this.cacheProvider.Get (ReferenceDataCacheContainer, cacheKey) as IEnumerable<string>;
if (data != null)
{
return data;
}
// retrieve from Repository
data = this.activitiesRepository.RetrieveStates();
this.cacheProvider.Add (ReferenceDataCacheContainer, cacheKey, data, TimeSpan.FromMinutes(60));
return data;
}
注意:请注意,该方法首先在“Reference”已命名缓 存中搜索状态列表,若未找到,则从 ActivityRepository 检索,并将其存储在缓存中,以备未来请求之 用。
所有实现的方法都将重复此行为。
6.实现 Retrieve 方法。为此,复制 CachedActivitiesRepository.cs 类中的以下代码:
(代码片段 – 增强 PlanMyNight MVC 应用程序– CachedActivitiesRepository RetrieveActivity)
C#
public Activity Retrieve (string id)
{
// retrieve from Cache; the Activity''s id is used as key
Activity data = this.cacheProvider.Get (ActivityCacheContainer, id) as Activity;
if (data != null)
{
return data;
}
// retrieve from Repository
data = this.activitiesRepository.Retrieve (id);
this.cacheProvider.Add(ActivityCacheContainer, id, data, TimeSpan.FromMinutes(15));
return data;
}
7.实现 RetrieveActivityTypes 方法。为此,复制 CachedActivitiesRepository.cs 类中的以下代码:
(代码片段 – 增强 PlanMyNight MVC 应用程序– CachedActivitiesRepository RetrieveActivityTypes)
C#
public IEnumerable<ActivityType> R
|