HowTo - WCF Caching Operation

The CachingOperationAttribute is used to cache WCF operation results and increase the system reactivity.

CachingOperationAttribute

This attribute can be set to either Business methods or WCF operations. When set on a Business method the attribute will be automatically set on the associated WCF operation (LayerCake Generator Process).

1. Standard way

When the result does not depend on the user context

// Business

[BusinessMethod]
[CachingOperation(Minutes = 30)]
public TCollection<Data> GetAllData(IUserContext userContext)
{
    TCollection<Data> collection = new TCollection<Data>();
    collection.Add(new Data { Content = "Result..." });

    return collection;
}

Timespan supported: Days, Hours, Minutes & Seconds.

When the result depends on the user context (each user has his own specific result)

// Business

[BusinessMethod]
[CachingOperation(Minutes = 30, WithUserContextDependency = true)]
public TCollection<Data> GetAllDataByUser(IUserContext userContext)
{
    TCollection<Data> collection = new TCollection<Data>();
    collection.Add(new Data { Content = string.Format("Result for user {0}...", userContext.Identifier) });

    return collection;
}

2. Advanced way

The second way gives the ability to define the key to generate using IKeyGenerator<T> interface.

// Business

[BusinessMethod]
[CachingOperation(Minutes = 30, KeyGeneratorType = typeof(GetDataKeyGenerator))]
public TCollection<Data> GetData(IUserContext userContext, long id)
{
    // ...
}

public class GetDataKeyGenerator : IKeyGenerator<string>
{
    public string Generate(object[] parameters)
    {
        // parameters contains the input parameters of the method

        IUserContext userContext = (IUserContext)parameters[0]; // can be used or not (depends on whether the user context is used)
        long id = (long)parameters[1];

        return string.Format("{0}_{1}", userContext.Identifier, id);
    }
}

KeyGenerator<T> Interface

The Generate() method must return unique key given the WCF operation parameters.

WCF Caching Operation process is handled in the CachingOperationInvoker class and can be easily customized.