Search code examples
c#sitecoreglass-mappersitecore8

Can Glass Mapper Sc create instance of mapping interface?


I am using Interface Mapping Concept in my project because my Sitecore items use/inherit multiple base templates. This worksnice but sometimes I need to create object that implements my template interface(ie. I want to add item to Sitecore) to do that I am forced to create a class that implements desired interface and than create object. Do I need to do that? Is there something in Glass.Mapper.Sc that returns proxy object I can use?


Solution

  • So I tried to imagine a possible scenario where you would use Castle's ProxyGenerator to generate an object based on one or more Interfaces. But I suspect you will run into problems because Glass's SitecoreService will expect a TypeConfiguration to work with, which you will not have if you generate a Proxy.

    However, creating a new item using an Interface should be possible like this:

    var service = new SitecoreService("master");
    var newItem = service.Create<IArticle, ISitecoreItem>(parentItem, "New item name");
    //populate the properties
    newItem.Introduction = "In the beginning there was a...";
    service.Save(newItem);
    

    ISitecoreItem is the type of the parent, you can use a common Interface for that. IArticle is the type of the new item.

    I havent tested this, but looking at the source code of Glass I do not see why this shouldnt work.