Skip to content

Instantly share code, notes, and snippets.

@Workshop2
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Workshop2/cff7f17065a3fc545ea5 to your computer and use it in GitHub Desktop.
Save Workshop2/cff7f17065a3fc545ea5 to your computer and use it in GitHub Desktop.
ObjectCache AddOrGetExisting extension method via Tasks and Actions/Funcs
public static class ObjectCacheExtensions
{
public async static Task<T> AddOrGetExisting<T>(this ObjectCache objectCache, string key, Func<Task<T>> action, CacheItemPolicy cacheItemPolicy)
{
T result;
if (objectCache.Contains(key))
{
result = (T)objectCache[key];
}
else
{
result = await action();
}
objectCache.Add(key, result, cacheItemPolicy);
return result;
}
}
public static class ObjectCacheExtensionTests
{
public class when_get_or_add_existing_when_key_doesnt_exist : SpecsFor<MemoryCache>
{
private readonly string _expectedResult = "This is what should be returned";
private readonly string _key = "myKey";
private string Result { get; set; }
protected override void InitializeClassUnderTest()
{
SUT = new MemoryCache("MyTest");
}
protected override void When()
{
Result = SUT.AddOrGetExisting<string>(_key, () => Task.Factory.StartNew(() => _expectedResult), new CacheItemPolicy()).Result;
}
[Test]
public void then_should_return_expected_value()
{
Result.ShouldEqual(_expectedResult);
}
[Test]
public void then_should_add_value_and_key_to_cache()
{
SUT.Contains(_key).ShouldBeTrue();
SUT[_key].ShouldEqual(_expectedResult);
}
}
public class when_get_or_add_existing_when_key_exist : SpecsFor<MemoryCache>
{
private readonly string _expectedResult = "This is what should be returned";
private readonly string _key = "myKey";
private string Result { get; set; }
protected override void InitializeClassUnderTest()
{
SUT = new MemoryCache("MyTest");
}
protected override void Given()
{
SUT.Add(_key, _expectedResult, new CacheItemPolicy());
}
protected override void When()
{
Result = SUT.AddOrGetExisting<string>(_key, () => Task.Factory.StartNew(() => "something else"), new CacheItemPolicy()).Result;
}
[Test]
public void then_should_return_expected_value()
{
Result.ShouldEqual(_expectedResult);
}
[Test]
public void then_should_add_value_and_key_to_cache()
{
SUT.Contains(_key).ShouldBeTrue();
SUT[_key].ShouldEqual(_expectedResult);
}
}
}
public async Task<UserStatus> GetStatusForUser(Guid userGuid)
{
string key = GetCacheName(userGuid);
return await _objectCache.AddOrGetExisting(key, () => _statusService.GetStatusForUser(userGuid), GenerateNewPolicy());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment