Accessing the Umbraco Services
Use Umbraco's service APIs to create, update, and delete core entities stored in the database from your custom code.
Services are defined using interfaces within the Umbraco.Cms.Core.Services namespace. To use the service APIs, you must first access them. Via the built-in dependency injection (DI) in ASP.NET Core, configured services are made available throughout Umbraco's codebase. This is achieved via injecting the specific service interface you require in the constructor of your class.
Access via a Controller
If you are accessing Umbraco services inside your own controller class, you can add the Umbraco services that you need as constructor parameters. An instance of every service will be provided at runtime from the service container. By saving each one to a local field, you can make use of them within the scope of your class:
public class CustomController
{
private readonly IContentService _contentService;
public ContentController(IContentService contentService)
{
_contentService = contentService;
}
public ActionResult PerformAction()
{
var someContent = _contentService.GetById(1234);
}
}Access via a Razor View Template
Inside a Razor View template, you can make use of a service injection into a view using the @inject directive. It works similarly to adding a property to the view, and populating the property using DI:
Access in a Custom Class via dependency injection
If you want to subscribe to notifications on one of the services, create a Composer C# class and add a custom NotificationHandler. In the NotificationHandler, inject the service you need into the public constructor. The underlying dependency injection framework will do the rest.
In this example, you will wire up to the ContentService 'Saved' event. You will create a new folder in the Media section whenever a new LandingPage is created in the content section to store associated media. Therefore, you will need the MediaService available to create the new folder.
Custom Class example
When you're creating your own class, in order to make use of the dependency injection framework, you need register the ICustomNewsArticleService service with the type CustomNewsArticleService. The AddScoped() method registers the service with the lifetime of a single request.
There are different ways that you can achieve the same outcome:
Register directly into Program.cs.
Another approach is to create an extension method on IUmbracoBuilder and call it from Program.cs.
When creating Umbraco packages you don't have access to Program.cs, therefore it's recommended to use a IComposer instead. A Composer gives you access to the IUmbracoBuilder.
Then your custom class, CustomNewsArticleService, can take advantage of the same injection to access services:
More information
Last updated
Was this helpful?