Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuring NHibernate second level caching in an MVC app

I have an MVC3 app that's using NHibernate. All was going well until I started to try and add second level caching. After browsing the web for a few hours I finally found what I think is the right dll (NHibernate.Caches.SysCache2.dll) and have added it to my project.

However, I can't find any help for configuring it with an MVC app. All the examples refer to having an App.config file (I presume this is for Web Forms). I'm a Java developer who's learning .Net so I'm not so familiar with how to rig everything up.

Could someone point me in the right direction. I'm using xml hibernate (hbm) files.

Thanks.

like image 458
Matt Avatar asked Jan 31 '11 17:01

Matt


1 Answers

I'm using 2nd level caching with MVC3 and NHibernate.Caches.SysCache.dll like this...

1st, add a config section to your web.config file like this

<configSections>
    <section name="syscache" type="NHibernate.Caches.SysCache.SysCacheSectionHandler, NHibernate.Caches.SysCache, Version=3.0.0.4000, Culture=neutral, PublicKeyToken=6876f2ea66c9f443"/>
</configSections>

add a syscache section to your web.config under your configuration section like this:

<syscache>
    <cache region="SomeCustomNameRegion" expiration="86400" priority="5" />
</syscache>

in my hibernate.cfg.xml file i have the following properties added:

<property name="cache.provider_class">NHibernate.Caches.SysCache.SysCacheProvider, NHibernate.Caches.SysCache</property>
<property name="cache.use_query_cache">true</property>
<property name="cache.use_second_level_cache">true</property>

I'm using FluentNhibernate to create my mappings and add this to support caching:

public CustomerClassMap()
{
    Cache.NonStrictReadWrite();
    Id(x => x.Id);
    Map(x => x.Name);
    //... more properties
}

And then in my data access code, I have something similar to this for queries that I want cached:

public IEnumerable<Customer> GetAllCached()
{
    return Session.CreateCriteria(typeof(Customer))
            .SetCacheable(true)
            .SetCacheRegion("SomeCustomNameRegion")
            .SetCacheMode(CacheMode.Normal)
            .AddOrder(Order.Desc("CreateDate"))
            .List<Customer>();
}

Here are some helpful links to get into a little more detail. There's nothing specific about MVC3 that you need to worry about, and most is unchanged from earlier versions of NHibernate as far as i can tell.

http://www.klopfenstein.net/lorenz.aspx/using-syscache-as-secondary-cache-in-nhibernate

http://blog.symbiotic-development.com/2008/02/27/more-configuring-nhibernate-caches/

like image 156
Chris Conway Avatar answered Sep 21 '22 17:09

Chris Conway