UmbracoHelper in Service not possible
# help-with-umbraco
p
Hey everyone, i ran into a problem, where it was not possible to use the UmbracoHelper in a Custom Service. Which service should i use to get the IPublishedContent i need?
c
Hi @PascalEugster! Using Dependency Injection you should be able to inject an instance of "UmbracoHelper" into your service through for example its constructor. The namespace for said class should be Umbraco.Cms.Web.Common. If you store that as _umbracoHelper and do a touch of refactoring you should be able to get the content like that.
p
When i do it with the UmbracoHelper i get this error:
System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: MD.Ornis.Ornis.Umb.Services.IArticleService Lifetime: Singleton ImplementationType: MD.Ornis.Ornis.Umb.Services.ArticleService': Cannot consume scoped service 'Umbraco.Cms.Web.Common.UmbracoHelper' from singleton 'MD.Ornis.Ornis.Umb.Services.IArticleService'.) ---> System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: MD.Ornis.Ornis.Umb.Services.IArticleService Lifetime: Singleton ImplementationType:
c
Aaah yes, the UmbracoHelper class is registered as a scope, as it depends on i.e. the published content request. You can only use that in Scoped services too
If you use a singleton service you need to use some other for of Umbraco service that is also a singleton
IIRC the IContentService is a singleton 🤔
p
hmmm but with the IContentService i only get the IContent not IPublishedContent objects
c
I see! The documentation says the following, you could give that a try: "If you need to use an UmbracoHelper in a service with a singleton lifetime you would instead need to make use of the IUmbracoHelperAccessor interface to obtain a temporary reference to an instance."
p
I think that made the trick! Thanks alot Corne! public IEnumerable GetAllArticles() { if (_examineManager.TryGetIndex("ExternalIndex", out IIndex? index)) { if (index != null) { var ids = index .Searcher .CreateQuery("content") .NodeTypeAlias(Article.ModelTypeAlias) .Execute() .Select(x => x.Id); foreach (var id in ids) { if (_umbracoHelperAccessor.TryGetUmbracoHelper(out var umbracoHelper)) { var content = umbracoHelper.Content(id); if(content is Article article) { yield return article; } } } } } }
c
That seems like it would work! Any time! 🙂
a
UmbracoHelper
is kind of a wrapper class that let's you access other things in Umbraco easier. So injecting an
IUmbracoContextAccessor
might be a slightly better option.
p
umbracoContext.Content.GetById() is the method then i think 🙂
a
Yes
p
Thanks Anders! 🙂
16 Views