Wednesday, April 4, 2012

Inside the MvcSiteMapProvider - Part 2: Dynamic node providers

Dynamic node providers gives you the ability to add dynamically generate nodes to the sitemap, fx. pages generated from a database. This is one of the most used extension points in the , and it is also easy to implement.


To implement a dynamic node provider you just have to derive from the DynamicNodeProviderBase class or the IDynamicNodeProvider interface. The difference between the interface and the abstract class, is that the DynamicNodeProviderBase doesn’t force define the caching, but defaults to no cache.
The IDynamicNodeProvider interface looks like this
public interface IDynamicNodeProvider
{
  IEnumerable<DynamicNode> GetDynamicNodeCollection();
  CacheDescription GetCacheDescription();
}
The methods are pretty much self explaining, GetDynamicNodeCollection, returns the nodes, and GetCacheDescription returns the cache description used for caching.
The CacheDescription is a helper class implemented in MvcSiteMapProvider, which simplifies cache settings. It contains the following properties:
Key
The key used in the cache.
Dependencies
The cache dependencies, is the normal CacheDependency object from .NET.
AbsoluteExpiration
Defines the cache's absolute expiration DateTime. Default is DateTime.MaxValue.
SlidingExpiration
The cache's sliding expiration TimeSpan. Default is zero, meaning no sliding expiration.
Priority
The cache items priority, defined by CacheItemPriority.
I would recommend to use some sort of caching in a dynamic node provider, especially nodes are provided from a database or another slow resource. The reason is that every time the sitemap or navigation are rendered the GetDynamicNodeCollection method will be called, unless caching is enabled, which could decrease performance quite a bit.
The DynamicNode class contains almost all the same properties which can be defined in the sitemap file, see “Creating a first sitemap” wiki page.
From a performance perspective the most important part in a dynamic node provider is the caching, making sure the correct caching has been defined really makes a difference.

15 comments: