NHibernate second-level caching - evicting regions

丶灬走出姿态 提交于 2019-11-30 21:33:26

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);
                }
            }
        }
    }

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!