Glass Mapper V4 – Configuration Maps

Something I had a look at quite a while back was the fluent configuration api in Glass. Unlike many developers, I am absolutely 100% fine with adding spaces to field names and don’t like using attribute based configuration in Glass. I talked about this in some detail a while ago in Introducing Glass Maps. I have since been through several iterations and finally settled on one that I like and therefore contributed to Glass itself. In essence, it is simply a neat way of bundling your fluent mapping into discrete units, which allows you to keep the mapping isolated from your POCO’s.

I understand this is not to every developers taste, but if you like to see clean .net objects, this my be the mapping configuration type for you.

We start off with the actual POCO to map to. In this case I have created a simple inherited structure like the one below:

{
    public interface ISitecoreItem
    {
        string Name { get; set; }

        string Url { get; set; }

        ID Id { get; set; }
    }

    public interface INavigation : ISitecoreItem
    {
        string Title { get; set; }

        string Summary { get; set; }
    }

The mapping classes

Then (elsewhere in your codebase) you need to create a simple class that inherits from either SitecoreGlassMap or UmbracoGlassMap, similar to the ones below.

    [ExcludeFromCodeCoverage] // Nothing to test
    public class SitecoreItemMap : SitecoreGlassMap<ISitecoreItem>
    {
        public override void Configure()
        {
            Map(x => x.AutoMap());
        }
    }

    [ExcludeFromCodeCoverage] // Nothing to test
    public class NavigationMap : SitecoreGlassMap<INavigation>
    {
        public override void Configure()
        {
            Map(x =>
            {
                ImportMap<ISitecoreItem>();
                x.Cachable();
            });
        }
    }

Adding the maps

By default then, the easiest way to add the configuration is to add the map to the appropriate section in the GlassScCustom.cs that is generated during Glass’ installation.

        public static void AddMaps(IConfigFactory<IGlassMap> mapsConfigFactory)
        {
            mapsConfigFactory.Add(() => new NavigationMap());
            mapsConfigFactory.Add(() => new SitecoreItemMap());
        }

Real World

In ‘real world’ scenario’s, I would simply override the dependencyResolver.ConfigurationMapFactory to use something like Castle Windsors ResolveAll() to get all of the maps from a given assembly.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s