Skip to the content

How to compose a custom service in Umbraco 9

What is a service in Umbraco 9 and why should you create one?

A service is a code repository for methods you commonly use throughout your project. If you have extended Umbraco in Version 8 or used Umbraco API then you will be familiar with both services and helpers. You know, the ContentHelper, ContentService, MediaService, MediaHelper etc. You might be used to using dependency injection to inject this into your controllers to do some custom Umbraco stuff.

If you did not already know, you can create custom helpers and services of your own to store commonly used methods and then expose these in the same way using dependency injection.

How did we expose custom helpers & services in Umbraco 8?

I will not go too deep into how to do this in Umbraco 8 since this article is specifically for Umbraco 9. I will mention however, that in Umbraco 8 we used to expose our services using ‘Composers’. Here is an example of how we used to ‘compose’ our custom services.

public class SiteHelperComposer : IUserComposer
{
     public void Compose(Composition composition)
     {
          composition.Register<ISiteHelper, SiteHelper>(Lifetime.Singleton);
     }
}

What has changed with Umbraco 9?

Not that much, which is good news. After learning a little bit about .Net Core I knew that helpers and services where usually exposed in the startup.cs. I was a little worried about this because it might cause a lot of headaches for package development.

This might still prove to be an issue in other areas but for exposing custom helpers and services this is not the case. Umbraco 9 still allows us to ‘compose’ helpers and services in much the same was as Umbraco 8 (Great!).

There are a few subtle differences with the way we ‘compose’…

Now a ‘composer’ will look like this.

public class SiteHelperComposer : IUserComposer
{
     public void Compose(IUmbracoBuilder builder)
     {
           builder.Services.AddSingleton<ISiteHelper, SiteHelper>();
      }
}

You will notice that both the signature is different and the way we add a ‘Singleton’.

Below is an example of a service I created and exposed using the AddSingleton method in Umbraco 9. This should be enough to get you started.

using System;
using Umbraco.Cms.Core.Composing;
using Microsoft.Extensions.Logging;
using Umbraco.Cms.Core.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
namespace Website.Core.Helpers
{
     public class SiteHelperComposer : IUserComposer
     {
          public void Compose(IUmbracoBuilder builder)
          {
                builder.Services.AddSingleton<ISiteHelper, SiteHelper>();
          }
     }
     public interface ISiteHelper
     {
          string TestMethod();
     }
     public class SiteHelper : ISiteHelper
     {
          private readonly ILogger<SiteHelper> _logger;
          public SiteHelper(ILogger<SiteHelper> logger)
          {
                _logger = logger;
          }
          public string TestMethod()
          {
                try
                {
                       throw new Exception();
                }
                catch (Exception e)
                {
                       _logger.LogError(e, "Index | Exception: {0} | Message: {1} | Stack Trace: {2}", e.InnerException != null ?                e.InnerException.ToString() : "", e.Message != null ? e.Message.ToString() : "", e.StackTrace);
                }
                return "This returned a value";
           }
     }
}

How to inject your custom service into a controller using dependency injection

This is done in the same way as it was with Umbraco 8. The code below will demonstrate this.

public HomePageController(ISiteHelper siteHelper, ILogger<HomePageController> logger)

Something else to point out…

Please also be aware that with Umbraco 9’s ILogger has changed. This is no longer the ILogger that was used in Umbraco 8. Instead, Umbraco 9 have dropped this and gone with Microsoft’s details logger. This means that if you inject the ILogger into your helpers, services, controllers then you have to do this a little differently. You will see this in my code above.

I wrote a separate article dedicated to the ILogger here.

I also wrote a separate article about the different ways to inject services here.

I hope this helps someone.

If anyone is having problems getting up and running with this then drop me a comment or reach out on LinkedIn.

About the author

David Armitage

Umbraco Community Builder | .Net MVC Developer | Umbraco Certified Master | Recruitment Professional

Hey Peeps,

I'm an entrepreneur and web developer with a passion for coding. I absolutely love working with Umbraco CMS and appreciate the Umbraco community even more.

I've got 10 years+ .Net experience and 7 years+ experience working in the recruitment industry, both coding and marketing job websites. I wanted to use my skills to help give something back to this awesome community and so I decided to build UmbraJobs.com.

My vision & fundamentals

I want this website to be a place where Umbraco Professionals and Umbraco Partners can advertise their services but at the same time I want to filter out all the under-qualified freelancers & agencies that take up the biggest part of other job & freelancer websites. We've all worked hard to gain our Umbraco certifications, partnership status, and help build the Umbraco community to what it is today. I want to see everyone get rewarded for their efforts.

Follow me on social media

If you're an Umbraco professional, partner, employer, recruiter or a passionate Umbraco community builder then I'm more than happy to hear from you. Follow me on my social media channels and please reach out if you have any needs, want help or consultation with anything Umbraco related or just want a general chat.

comments powered by Disqus

Blog Filter


How we can help?

Need help with an Umbraco project?

Need help with a project but not too sure who to approach? Send us your project brief and budget. We will provide a free consultation and can help you gather quotes from the best and most suitable freelancers or agencies.

Looking to hire an Umbraco Professional?

Have you got job vacancy and want to hire an Umbraco professional? Post a job on our website for free. Alternatively let us know your requirements and we will send suitable prospects your way.

Claim your free profile!

Are you an Umbraco Freelance Developer or Umbraco partner that wants to advertise on our site? If you work with Umbraco or registered as an Umbraco partner then you can create a profile for free.

Let's build the Umbraco Community

We're big on building the Umbraco community and we think you guys are awesome! If there's anyway at all we can help then please reach out.