Using Umbraco Content Service outside of Umbraco context/control in Umbraco 6

In order to make user of IContentService outside of Umbraco Controllers/Views/etc you're going to need to expose it. Much in the same way you'd setup NHibernate to create a session factory on application start we grab IContentService and make it accessible. In this case via UmbracoApplication.UmbContentService

UmbracoApplication.cs

namespace XXX.UI  
{
  using System.Web.Http;
  using System.Web.Mvc;
  using System.Web.Routing;
  using Umbraco.Core;
  using Umbraco.Core.Services;

    public class UmbracoApplication : IApplicationEventHandler
  {
    public static IContentService UmbContentService { get; private set; }

    //Normal crap the interface throws out here

    public void OnApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
    {
            UmbContentService = ApplicationContext.Current.Services.ContentService;
        }

  }

We can then use this throughout the application to create a simple '/Base' service to access content. For example to get a template from Umbraco (by name) we could create the following simple implementation.

UmbracoEmailTemplateHelper.cs

namespace XXX.UI.App.UmbracoBase  
{
  using System.Linq;
  using Umbraco.Core.Services;

    [Umbraco.Web.BaseRest.RestExtension("EmailTemplateHelpers")]
    public class UmbracoEmailTemplateHelper
    {
        private static readonly IContentService ContentService = UmbracoApplication.UmbContentService;

        [Umbraco.Web.BaseRest.RestExtensionMethod]
        public static string GetEmailTemplate(string templateName)
        {
            var template = ContentService.GetChildrenByName(ContentService.GetChildrenByName(-1, "Email Templates")
                                                                          .First()
                                                                          .Id, templateName).First();

            if (template == null || template.Properties.Count < 1 || template.Properties["template"] == null) 
            return string.Empty;

      return template.Properties["template"].Value.ToString();
        }
    }
}

You an of course hook it up to your IOC container of choice; in my case Ninject is hooked up as follows.

using Umbraco.Core;  
using global::Ninject.Modules;

public class UmbracoModule : NinjectModule  
{
        public override void Load()
        {
                Kernel.Bind<Umbraco.Core.Services.IContentService>()
                      .ToMethod(x => ApplicationContext.Current.Services.ContentService);
                Kernel.Bind<Umbraco.Core.Services.IContentTypeService>()
                      .ToMethod(x => ApplicationContext.Current.Services.ContentTypeService);
        }
}
Chris McKee

Chris McKee

https://chrismckee.co.uk

Software Engineer, Web Front/Backend/Architecture; all-round tech obsessed geek. I hate unnecessary optimism

View Comments