Life Through A Lens – Using your own IoC container with Glass Mapper

This should be a nice quick post, but when I look back, it’s something I have done on every project I have used Glass Mapper on.

Glass’ out of the box Castle Windsor implementation tends to create it’s own IWindsorContainer during Sitecore’s initialise pipeline (formerly done using WebActivator). This is great if you want to get up and running quickly, but in my case – especially with the new Delegate mapping function available, I often find that I would rather have a more global container than this, since – for example, some of the delegate mapping does use dependencies from my codebase.

In this post I will quickly describe how to use an external Castle Windsor container with Glass Mapper. If you want to find out more on using other IoC containers including Autofac, StructureMap or Unity as the container for Glass, please take a look at Glass Mapper On Agnostic IoC

Firstly – we simply modify the GlassMapperSc class to add ourselves a DependencyResolver property and a change the Start() method accordingly to set it.

using Glass.Mapper;
using Glass.Mapper.Sc.CastleWindsor;
using Sitecore.Pipelines;

namespace MyGlassApp.App_Start
	public class GlassMapperSc
		public void Process(PipelineArgs args){

                // THIS LINE ADDED
		internal static DependencyResolver DependencyResolver { get; private set; }

		public static void Start()
	            // THIS LINE ADDED Changed to create the resolver
                    DependencyResolver = GlassMapperScCustom.GetResolver() ?? DependencyResolver.CreateStandardResolver();

		    //install the custom services

                    //create a context
                    var context = Context.Create(DependencyResolver);


Then – in the MyGlassApp.App_Start.GlassMapperScCustom class, simply add the following method

        public static DependencyResolver GetResolver()
            IWindsorContainer myContainer = SomewhereElse.MyContainer; // get myContainer from wherever you choose in your application

            // Create a custom resolver here, otherwise the default glass one will be used
            return new DependencyResolver(myContainer); 

The Glass dependencies should then be registered to your external container.


I will be submitting this change as a more permanent one for Glass Mapper, but in the mean time, it’s a nice simple way of using your own windsor container as a container for use with Glass Mapper.

Leave a Reply

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

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