Welcome to the navigation

Dolore duis magna voluptate irure sed eiusmod sit anim nisi excepteur ut commodo officia in ex reprehenderit adipisicing quis ea velit pariatur, dolore fugiat ullamco. Reprehenderit ex exercitation anim laboris ad nostrud voluptate aliquip nisi adipisicing eiusmod deserunt ut ullamco pariatur, et in nulla velit sint sunt duis commodo quis

Yeah, this will be replaced... But please enjoy the search!

Injecting Umbraco IContentService into a Unity Container

I've been using Unity with Umbraco ModelsBuilder for a while. Figured I should share some of my snippets. Here is how you inject IContentService into the Unity Container.

About IContentService

From the docs: Defines the ContentService, which is an easy access to operations involving IContent. https://our.umbraco.com/apidocs/csharp/api/Umbraco.Core.Services.IContentService.html

Using with Unity

Unity, the Microsoft IoC Container. 

// Injecting existing contentservice instance into the unity container
// Eric Herlitz - www.herlitz.io
container.RegisterType(
    lifetimeManager: new SingletonLifetimeManager(),
    injectionMembers: new InjectionFactory(
        c => ApplicationContext.Current.Services.ContentService
    ));
Nothing fancy to it really, we simply register the singleton instance from ApplicationContext.Current.Services.ContentService with the interface in the Unity IoC Container.

Usage

public class WhateverService
{
    private readonly IContentService _contentService;

    public WhateverService(IContentService contentService)
    {
        _contentService = contentService;
    }

    public string GetNameById(int id)
    {
        return $"The name of the node is {_contentService.GetById(id).Name}";
    }

    public IContent GetById(int id)
    {
        return _contentService.GetById(id);
    }
}

Unity will inject the IContentService using constructor injection and expose it in the _contentService variable. This will work in any injectable object in Umbraco as well as custom implementations and classes.