|
The ClearCache attribute clears cached data for the provided method.
ClearCacheAspect.cs
using System;
using NUnit.Framework;
using BLToolkit.Aspects;
using BLToolkit.Reflection;
namespace HowTo.Aspects
{
[TestFixture]
public class ClearCacheAspect
{
public abstract class TestClass
{
public static int Value;
// This is a method we will cache. Cached return value depends on input parameters.
// We will change the 'Value' field outside of the class and see how it affects the result.
//
[Cache(MaxCacheTime=500, IsWeak=false)]
public virtual int CachedMethod(int p1, int p2)
{
return Value;
}
// This method clears the CachedMethod cache.
//
[ClearCache("CachedMethod")]
public abstract void ClearCache();
// The CachedMethod is specified by name and parameters.
// Also you can use declaring method type.
//
[ClearCache("CachedMethod", typeof(int), typeof(int))]
public abstract void ClearCache2();
// This method clears all caches for provided type.
//
[ClearCache(typeof(TestClass))]
public abstract void ClearAll();
// This method clears all caches for current type.
//
[ClearCache]
public abstract void ClearAll2();
public static TestClass CreateInstance()
{
// Use TypeAccessor to create an instance of an abstract class.
//
return TypeAccessor<TestClass>.CreateInstance();
}
}
[Test]
public void Test()
{
TestClass tc = TypeAccessor<TestClass>.CreateInstance();
TestClass.Value = 1;
int value1 = tc.CachedMethod(1, 2);
TestClass.Value = 2;
int value2 = tc.CachedMethod(1, 2);
// The cached values are equal.
//
Assert.AreEqual(value1, value2);
tc.ClearCache();
TestClass.Value = 3;
// Previous and returned values are not equal.
//
Assert.AreNotEqual(value1, tc.CachedMethod(1, 2));
tc.ClearCache2();
}
}
} |
BLToolkit type builder will generate the following for the class above:
[BLToolkitGenerated]
public sealed class TestClass : ClearCacheAspect.TestClass
{
private static MethodInfo _methodInfo1;
private static MethodInfo _methodInfo2;
private static Type _type3;
private static Type _type4;
public override int CachedMethod(int p1, int p2)
{
// Method implementation.
}
public override void ClearCache()
{
try
{
// Here should be main method implementation.
// It is empty as this method does nothing.
}
finally
{
if (_methodInfo1 == null)
{
_methodInfo1 =
ClearCacheAspect.GetMethodInfo(this, null, "CachedMethod", null);
}
CacheAspect.ClearCache(_methodInfo1);
}
}
public override void ClearCache2()
{
try
{
}
finally
{
if (_methodInfo2 == null)
{
_methodInfo2 = ClearCacheAspect.GetMethodInfo(
this,
null,
"CachedMethod",
new Type[] { typeof(int), typeof(int) });
}
CacheAspect.ClearCache(_methodInfo2);
}
}
public override void ClearAll()
{
try
{
}
finally
{
if (_type3 == null)
{
_type3 = ClearCacheAspect.GetType(this, typeof(TestClass));
}
CacheAspect.ClearCache(_type3);
}
}
public override void ClearAll2()
{
try
{
}
finally
{
if (_type4 == null)
{
_type4 = ClearCacheAspect.GetType(this, null);
}
CacheAspect.ClearCache(_type4);
}
}
} |
| |