Using Glass.Mapper with fluent configuration in a Helix solution

NB. I have since written a part 2 to this blog post offering a better approach

If you’re using fluent configuration, the Glass site shows us how to register the mapping:

mapsConfigFactory.Add(() => new MenuItemConfig());

But if we have our Glass project in the Foundation layer (where we find GlassMapperScCustom.cs), and the class MenuItemConfig is in the Feature layer, we’ve gone against Helix principles as our layers should only depend on a layer more stable than themselves.

The solution is to find any instances of IGlassMap in our solution, and then we can automate our mapping registration. To do this we edit the AddMaps method found in GlassMapperScCustom.cs:

public static void AddMaps(IConfigFactory<IGlassMap> mapsConfigFactory)
        {
            // Add maps here
            var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(x => x.FullName.IndexOf("Helixbase", StringComparison.OrdinalIgnoreCase) >= 0);

            var glassmapType = typeof(IGlassMap);

            foreach (var assembly in assemblies)
            {
                var mappings = assembly.GetTypes().Where(x => glassmapType.IsAssignableFrom(x));

                foreach (var map in mappings)
                {
                    mapsConfigFactory.Add(() => Activator.CreateInstance(map) as IGlassMap);
                }
            }
        }

We can now use Glass Mapper with Helix – we’ve also automated mapping registration!

5 thoughts on “Using Glass.Mapper with fluent configuration in a Helix solution

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s