TIHIDI: Install and Configure Glass Mapper 4.x for Sitecore 8.x MVC Solution with Simple Injector 3.x

This blog post will go through how I setup Glass Mapper in a Visual Studio 2015 MVC solution for Sitecore 8.1. I have used other Sitecore ORM solutions but finally ended up liking Glass. Mike Edwards and Nathanael Mann were patient enough to teach me Glass in a short amount of time and the Glass training helped a lot as well.

Visit http://www.glass.lu/mapper/sc for more information on Glass Mapper for Sitecore.

TIHIDI: Stands for This Is How I Do It. I am going to write a series of blog posts going through how I do Sitecore related work. Hope it helps you!

As usual we will be using NuGet to get the current stable version of Glass, which at this moment is 4.1.2.67.

Before we run the install package for Glass, make sure you have Sitecore.Kernel.dll, Sitecore.Mvc.dll and System.Web.Mvc.dll referenced in your project, which I do since I have been using the same solution for my blog posts.

glass1

Once Glass is installed, create two class library solutions, one called Mapping and one called Models.

I create hand coded (yes hand coded you lazy farts!) Models which are true .NET classes or interfaces. These will use .NET types along with Glass field types.

I do the mapping separately in the Mapping project. If the Model can auto map we can add it to the auto maps. If not, we create a specific mapping class for that Model to tackle the mapping.

Install Glass on these two projects as well.

In the SimpleInjector.cs class we will be registering all business logic functionality along with Glass mapping classes. Here is the sample code for SimpleInjector.cs:

using SimpleInjector.Packaging;
using System;
using SimpleInjector;
using Glass.Mapper.Sc;
using System.Reflection;
using System.Collections.Generic;
using Glass.Mapper.Maps;
using System.Linq;
using TIHIDI.SCExtensions.DI;
using TIHIDI.Business.GlassSC;
using TIHIDI.Business.Content;

namespace TIHIDI.Web.App_Start
{
    public class SimpleInjector:IPackage
    {
        public void RegisterServices(Container container)
        {
            container.Register(() => new SitecoreContext());
            container.Register(() => new GlassHtml(container.GetInstance()));
            container.Register(()=> new ControllerSCContext(container.GetInstance()));

            //register all Glass mapping classes
            string assemblyName = ".Mapping";

            IEnumerable assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(x => x.FullName.IndexOf(assemblyName, StringComparison.OrdinalIgnoreCase) >= 0);
            Type glassmapType = typeof(IGlassMap);

            List maps = new List();
            foreach (Assembly assembly in assemblies)
            {
                if (maps.Count == 0)
                    maps = assembly.GetTypes().Where(x => glassmapType.IsAssignableFrom(x)).ToList();
                else
                    maps.AddRange(assembly.GetTypes().Where(x => glassmapType.IsAssignableFrom(x)).ToList());
            }
            container.RegisterCollection(maps);
        }
    }
}

Following this, lets get to the GlassMapperSCCustom.cs file in order to add our maps so that Glass can handle them. Here is the sample code for GlassMapperSCCustom.cs:

	public static void AddMaps(IConfigFactory mapsConfigFactory)
        {
            // Add maps here
            // mapsConfigFactory.Add(() => new SeoMap());
            ContainerManager containerManager = new ContainerManager();
            
            foreach (var map in containerManager.Container.GetAllInstances())
            {
                mapsConfigFactory.Add(() => map);
            }
        }

Once this is done we have to go and modify our App_Config > Include > SimpleInjector > SimpleInjector.config file to load the Initialize of the Simple Injector before Glass. Here is the updated config file:


  
    
      
        
      
    
  

Now lets add a simple TextBlock template in Sitecore for demo purposes, here is the sample template:

glass5

In the Models project add IGlassBase, here is the sample code for the interface:

using Sitecore.Globalization;
using System;
using System.Collections.Generic;

namespace TIHIDI.Models
{
    public interface IGlassBase
    {
        Guid Id { get; set; }

        Language Language { get; set; }

        int Version { get; set; }

        IEnumerable BaseTemplateIds { get; set; }

        string TemplateName { get; set; }

        Guid TemplateId { get; set; }

        string Name { get; set; }

        string Url { get; set; }
    }
}

Lets also add an interface to represent our template called ITextBlock. Here is the sample code for the interface:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TIHIDI.Models.Templates.Content
{
    public interface ITextBlock : IGlassBase
    {
        string Heading { get; set; }
        string SubHeading { get; set; }
        string Content { get; set; }
    }
}

Next we need a way to inform Glass as to how it needs to map these interfaces. We will begin my adding a GlassBaseMap class, here is the sample code:

using Glass.Mapper.Sc.Configuration;
using Glass.Mapper.Sc.Maps;
using TIHIDI.Models;

namespace TIHIDI.Mapping
{
    public class GlassBaseMap : SitecoreGlassMap
    {

        public override void Configure()
        {
            Map(x =>
            {
                x.AutoMap();
                x.Info(y => y.BaseTemplateIds).InfoType(SitecoreInfoType.BaseTemplateIds);
            });
        }
    }
}

For all simple mappings I dump them into a class called PureAutoMaps, so lets create a class and add that mapping. Here is the sample code:

using Glass.Mapper.Sc.Maps;
using TIHIDI.Models;
using TIHIDI.Models.Templates.Content;

namespace TIHIDI.Mapping
{
    public class PureAutoMaps
    {
    }

    public class TextBlockMap : SitecoreGlassMap
    {

        public override void Configure()
        {
            Map(x =>
            {
                ImportMap();
                x.AutoMap();
            });
        }
    }
}

There is no reason to inherit the IGlassBase except that it provides some additional attributes. You would need the Id attribute in order for you to make this editable in the Experience editor. Again this is just an example, we can highly simplify this as well.

Notice the way you are able to use ImportMap and pull in inherited classes/interfaces. Also notice how we used Automap and .Info in order to specify what Glass needs to do with the BaseTemplateIds. We will get into this in a lot more detail later.

Rebuild and deploy. Sites come up fine. Let check the ShowConfig.aspx.

glass4

If you have any questions or concerns, please get in touch with me. (@akshaysura13 on twitter or on Slack).

4 thoughts on “TIHIDI: Install and Configure Glass Mapper 4.x for Sitecore 8.x MVC Solution with Simple Injector 3.x”

  1. Hi Akshay,
    Can you please explain the pipeline (TIHIDI.SCExtensions.DI.Pipelines.InitializeSimpleInjectorControllerFactory) which is patched in “SimpleInjector.config” . I don’t see this pipeline explained in this blog .

  2. Hi Akshay,
    You say you dump all simple mappings in to a “PureAutoMaps” class but the definition of PureAutoMaps in your code block above is empty. What am I missing / misunderstanding here ?

  3. It is just used as a shell cs file. We are dumping multiple classes inside of that cs file.

Leave a Reply

Your email address will not be published. Required fields are marked *