Search code examples
asp.net-mvcsitecoreunity-containerglass-mapper

Glass Mapper + Unity


I understand that the Glass Mapper v4 can now be used in conjunction with any IoC container. But I'm struggling to find a code example of how to achieve this.

I want to be able register glass components and inject them into my controllers using Unity, for example:

public class SearchController : Controller
{
    private readonly ISitecoreContext _context;

    //Inject via Unity
    public SearchController(Glass.Mapper.Sc.ISitecoreContext context)
    {
        _context = context;
    }
}

Can someone provide a code example for how to get Glass linked up with Unity?


Solution

  • You don't actually need an IoC container to configure the basic mapping setup for Glass anymore.

    Instead, configure a registration for ISitecoreContext and a custom MVC controller factory overriding the requisite ReleaseController and GetControllerInstance methods.

    My Unity is a little rusty but something like this (you might find something simpler):

    IUnityContainer container = new UnityContainer()
    container.RegisterType<ISitecoreContext, SitecoreContext>(new HierarchicalLifetimeManager(), new InjectionFactory(x => new SitecoreContext()));