NHibernate Layer 2 Caching - Eviction of Regions

We have several areas of caching created in our implementation of nHibernate. To avoid problems with load-balanced servers, I want to effectively disable caching on pages that edit cached data. I can write a method that completely clears all query caches, class caches, and my entity.

But I really want to clear the cache by region. sessionFactory.EvictQueries () will accept the scope parameter, but Evict () and EvictCollection () do not. I really don't want to throw away the entire cache here, and I don't want to maintain some kind of clumsy dictionary associating types with their cache areas. NHibernate has a way to query an entity or collection, what are its caching settings?

thank

+5
source share
2 answers

I just did the same. For each benefit, here is the method I built:

public void ClearCache(string regionName)
    {
        // Use your favourite IOC to get to the session factory
        var sessionFactory = ObjectFactory.GetInstance<ISessionFactory>();

        sessionFactory.EvictQueries(regionName);

        foreach (var collectionMetaData in sessionFactory.GetAllCollectionMetadata().Values)
        {
            var collectionPersister = collectionMetaData as NHibernate.Persister.Collection.ICollectionPersister;
            if (collectionPersister != null)
            {
                if ((collectionPersister.Cache != null) && (collectionPersister.Cache.RegionName == regionName))
                {
                    sessionFactory.EvictCollection(collectionPersister.Role);
                }
            }
        }

        foreach (var classMetaData in sessionFactory.GetAllClassMetadata().Values)
        {
            var entityPersister = classMetaData as NHibernate.Persister.Entity.IEntityPersister;
            if (entityPersister != null)
            {
                if ((entityPersister.Cache != null) && (entityPersister.Cache.RegionName == regionName))
                {
                    sessionFactory.EvictEntity(entityPersister.EntityName);
                }
            }
        }
    }
+4
source

OK, it seems I answered my question. The default interface that returned when nHibernate metadata was output does not provide caching information, however, if you dig into its implementations, it is. A bit clumsy, but he does the job.

0
source

All Articles