2

I've made a convention that allow caching of all entites by default. But for some entites I want to remove caching. I thought about using AutoMappingOverriding but I don't know if it is possible to say NoCache in AutoMappingOverriding.

Thanks,

Yann
  • 1,388
  • 2
  • 11
  • 9

1 Answers1

1

Using another slightly related post I came up with the following:

// setup caching
var typesToIgnoreForCaching = new Type[] { typeof(Type1ToNotCache), typeof(Type2ToNotCache) };
var typesToCache = typeof(IEntity).Assembly.GetTypes().Where(t => config.ShouldMap(t)
            && !typesToIgnoreForCaching.Contains(t)).ToList();
 var cacheOverride = new CacheOverride();
 cacheOverride.DoOverrides(m, typesToCache);

The CacheOverride class is as follows:

class CacheOverride : PersistenceOverride<object>
{
    public override Action<AutoMapping<T>> MyOverride<T>()
    {
        return am =>
        {
            am.Cache.ReadWrite();
        };
    }
}

Where the PersistenceOverride class is:

abstract class PersistenceOverride<I>
{
    public void DoOverrides(AutoPersistenceModel model, IEnumerable<Type> Mytypes)
    {
        foreach (var t in Mytypes.Where(x => typeof(I).IsAssignableFrom(x)))
            ManualOverride(t, model);
    }

    private void ManualOverride(Type recordType, AutoPersistenceModel model)
    {
        var t_amt = typeof(AutoMapping<>).MakeGenericType(recordType);
        var t_act = typeof(Action<>).MakeGenericType(t_amt);
        var m = typeof(PersistenceOverride<I>)
                .GetMethod("MyOverride")
                .MakeGenericMethod(recordType)
                .Invoke(this, null);
        model.GetType().GetMethod("Override").MakeGenericMethod(recordType).Invoke(model, new object[] { m });
    }

    public abstract Action<AutoMapping<T>> MyOverride<T>() where T : I;
}

Essentially, all this does is go through the list of entities in your domain, via reflection, and manually override each entity with your convention caching strategy. You just need to add whichever types you don't want caching to typesToIgnoreForCaching.

Also, you'll need to modify the typesToCache line so that it corresponds to however you've set up your domain.

Thanks to Tom for the code to produce an Action<AutoMapping<T>>

Community
  • 1
  • 1
Mark Jerzykowski
  • 812
  • 8
  • 15