问题
We have a number of cache regions set up in our nHibernate implementation. In order to avoid trouble with load balanced web servers, I want to effectively disable the caching on the pages that edit the cached data. I can write a method that clears out all my query caches, my class caches and my entity caches easily enough.
But what I really want is to clear the cache by region. sessionFactory.EvictQueries() will take a region parameter, but Evict() and EvictCollection() does not. I don't really want to throw away the whole cache here, nor do I want to maintain some sort of clumsy dictionary associating types with their cache regions. Does nHibernate have a way to ask an entity or collection what its caching settings are?
thanks
回答1:
I've just done the same thing. For everyone's benefit, here is the method I constructed:
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);
}
}
}
}
回答2:
OK, looks like i've answered my own question. The default interface that's returned when you pull out the nHibernate metadata doesn't provide information on caching, however if you dig around in the implementations of it, it does. A bit clumsy, but it does the job.
来源:https://stackoverflow.com/questions/9433514/nhibernate-second-level-caching-evicting-regions