NHibernate is a popular Object-Relational Mapping (ORM) framework for .NET applications, which enables seamless database interactions through object-oriented code. However, when applications handle a high volume of transaction loads, they often experience performance bottlenecks due to frequent database queries.
To address this, NHibernate provides Second-Level Caching, which keeps objects in memory at the application level, reducing the need to repeatedly access the database. NCache, an extremely fast and scalable distributed cache, acts as an NHibernate Second-Level Cache provider, which significantly improves application speed, scalability, and reliability.
<configuration>
<application-config application-id="myapp"
enable-cache-exception="true"
default-region-name="default">
<cache-regions>
<region name="default"
cache-name="mycache"
priority="default"
expiration-type="absolute"
expiration-period="300" />
</cache-regions>
</application-config>
</configuration>
<configuration>
<application-config application-id="myapp"
enable-cache-exception="true">
<database-dependencies>
<dependency entity-name="Orders"
type="sql"
sql-statement="SELECT OrderID FROM Orders WHERE OrderDate > GETDATE()-1"
cache-key-format="dependency.order:[OrderID]" />
</database-dependencies>
</application-config>
</configuration>
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
IQuery query = session.CreateQuery("FROM Customer c")
.SetCacheable(true);
var customers = await query.ListAsync<Customer>();
var newCustomer = new Customer { Name = "John Doe" };
await session.SaveAsync(newCustomer);
await session.FlushAsync();
transaction.Commit();
}
}
Install-Package NHibernate.NCache
Modify your NHibernate configuration files to enable NCache as the second-level cache provider.
Update hibernate.cfg.xml
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="cache.provider_class">
Alachisoft.NCache.Integrations.NHibernate.Cache.NCacheProvider,
Alachisoft.NCache.Integrations.NHibernate.Cache
</property>
<property name="cache.use_second_level_cache">true</property>
<property name="cache.use_query_cache">true</property>
</session-factory>
</hibernate-configuration>
© Copyright Alachisoft 2002 - 2025. All rights reserved. NCache is a registered trademark of Diyatech Corp.