1 December 2015

Part 3: Page History: IoC using Sitecore API

Following my previous post, I wanted to do a quick Parenthese to talk about simple IoC. Like most of the developers out there we are usually going for Castle.Windosr as IoC on most of our projects. This is working quite nicely in most of the cases and it is quite nice. However, on this special instance, my module code is actually really simple and it feels like Castle.Windsor would be quite an overkill... This would also add another dependency to Castle.Windsor which I did not want. Lucky there is another way using only Sitecore API. Since we already have a dependency on Sitecore then it is fine. Secondly this is really simple to implement... This is based on the great blog post from Anders Laub Christoffersen http://sitecorepromenade.blogspot.com.au/2015/12/part-2-page-history-code-to-retrieve.html

so what is it all about. Well this solution is using Sitecore Type Mapping to resolve your custom types. So what we do is add a configuration patch to add the following section:


  
    
      
      
    
  



This type mapping "type" attribute will point to classes that implement the Interfaces we need to resolve using the IoC. The next step is to write resolver class that will be used to look at the configuration typeMappings and create the object based on the "Type" attribute in from the configuration

    public class TypeResolver
    {
        public static T Resolve(string typeName, object[] parameters = null)
        {
            var xpath = "typeMappings/mapping[@name='" + typeName + "']";
            return (T)(parameters == null ?
              Sitecore.Reflection.ReflectionUtil.CreateObjectFromConfig(xpath) :
              Sitecore.Reflection.ReflectionUtil.CreateObjectFromConfig(xpath, parameters));
        }
    }



we can now use the class to resolve our interfaces based on the config. For instance on our controller, we will be able to do something like

    public class OPageHistoryController : System.Web.Mvc.Controller
    {
        private IPageHistoryService pageHistoryService = TypeResolver.Resolve("PageHistoryService");

        /// 
        /// get the full item history information including the renderings datasources
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public ActionResult GetCurrentItem(string id, string database, string language, string version)
        {
            return Json(pageHistoryService.GetPageHistory(id, database, language, version), JsonRequestBehavior.AllowGet);

        }
    }

2 comments:

  1. Nice Post! It is really interesting to read from the beginning & I would like to share your blog to my circles, keep sharing… Sitecore Online Training

    ReplyDelete