Skip to content
Igor Tkachev edited this page May 20, 2016 · 1 revision

Home / Aspects

Cache aspect can be applied to entire class. In this case all virtual and abstract member calls will be cached. However you can use the NoCache attribute to exclude particular members from caching.

NoCache.cs

using System;

using NUnit.Framework;

using BLToolkit.Aspects;
using BLToolkit.Reflection;

namespace HowTo.Aspects
{
    [Cache]
    public abstract class NoCacheTestClass
    {
        public static int Value;

        public virtual int CachedMethod(int p1, int p2)
        {
            return Value;
        }

        [NoCache]
        public virtual int NoCacheMethod(int p1, int p2)
        {
            return Value;
        }

        public static NoCacheTestClass CreateInstance()
        {
            // Use TypeAccessor to create an instance of an abstract class.
            //
            return TypeAccessor<NoCacheTestClass>.CreateInstance();
        }
    }

    [TestFixture]
    public class NoCacheAttributeTest
    {
        [Test]
        public void Test()
        {
            NoCacheTestClass t = TypeAccessor<NoCacheTestClass>.CreateInstance();

            NoCacheTestClass.Value = 1; Assert.AreEqual(1, t.CachedMethod(1, 1));
            NoCacheTestClass.Value = 2; Assert.AreEqual(1, t.CachedMethod(1, 1)); // no change

            NoCacheTestClass.Value = 3; Assert.AreEqual(3, t.NoCacheMethod(2, 1));
            NoCacheTestClass.Value = 4; Assert.AreEqual(4, t.NoCacheMethod(2, 1));
        }
    }
}
Clone this wiki locally