Search code examples
umbracoumbraco8

Unable to use SaveAndPublish from ContentService


I'm trying to save my IContent called child, but on this line(contentService.SaveAndPublish(child);) I get the following error: Object reference not set to an instance of an object.

if (child.HasProperty("navn"))
{
    child.SetValue("navn", worker.Name.ToString(), "da-dk");
}
contentService.SaveAndPublish(child);

This is how I define my contentService:
IContentService contentService = Umbraco.Core.Composing.Current.Services.ContentService;

And I'm finding the children like this:

long totalChildren;

IEnumerable<IContent> children = contentService.GetPagedChildren(filialsParent.Id, 0, 100, out totalChildren);

´ Can someone point out what is wrong here?


Solution

  • I found out that if I do this then it works.

    var umbf = Umbraco.Web.Composing.Current.Factory.GetInstance<IUmbracoContextFactory>();
    using (var contextf = umbf.EnsureUmbracoContext())
    {
        var umbcontext = contextf.UmbracoContext;
        IContentService cs = Umbraco.Core.Composing.Current.Services.ContentService;
        cs.SaveAndPublish(child);
    
    }