Craig100
08/05/2023, 5:46 PMservices.AddTransient<Helpers>();
to ConfigureServices in startup.cs but that just gives me:
Unhandled exception. System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Web.Core.Services.Helpers Lifetime: Transient ImplementationType: Web.Core.Services.Helpers': Unable to resolve service for type 'Umbraco.Cms.Core.Models.PublishedContent.IPublishedContent' while attempting to activate 'Web.Core.Services.Helpers'.)
So I have:
Namespace: myProj.Core.Services
Class: Helpers (with various methods)
Then what?
Thanks.Maarten
08/05/2023, 6:32 PMCraig100
08/05/2023, 6:56 PMpublic class Helpers {
private readonly IPublishedContent _publishedContent;
private readonly IPublishedContentQuery _contentQuery;
public Helpers(IPublishedContent publishedContent, IPublishedContentQuery contentQuery) {
_publishedContent = publishedContent;
_contentQuery = contentQuery;
}
public IPublishedContent? GetMemorialListNode() {
IPublishedContent? siteRoot = _contentQuery.ContentAtRoot().FirstOrDefault();
var memorialListNode = siteRoot?.FirstChild<MemorialListPage>();
return memorialListNode;
}
}
Craig100
08/05/2023, 6:57 PMDan 'Diplo' Booth
08/05/2023, 7:41 PMIPublishedContent
from the constructor, as it can't be injected.D_Inventor
08/05/2023, 8:06 PMIPublishedContent
is not registered in the container: it is produced by methods on the Umbraco context, therefore you cannot take dependency on IPublishedContent
.Craig100
08/06/2023, 10:36 AMRachel D
08/06/2023, 10:49 AMIUmbracoContextAccessor
to get access to thatRachel D
08/06/2023, 10:53 AMcsharp
if (umbracoContextAccessor.TryGetUmbracoContext(out var umbracoContext))
{
[... code here]
}
Craig100
08/06/2023, 10:55 AMpublic class Helpers {
private readonly IUmbracoContextAccessor _umbracoContextAccessor;
public Helpers(IUmbracoContextAccessor umbracoContextAccessor)
{
_umbracoContextAccessor = umbracoContextAccessor;
}
public IPublishedContent GetMemorialListNode() {
if (_umbracoContextAccessor.TryGetUmbracoContext(out IUmbracoContext? context) == false) {
return null; //this.Problem("unable to get content");
}
if (context.Content == null) {
return null; //this.Problem("Content Cache is null");
}
IPublishedContent? siteRoot = context.Content.GetAtRoot().FirstOrDefault();
var memorialListNode = siteRoot?.FirstChild<MemorialListPage>();
return memorialListNode;
}
}
Rachel D
08/06/2023, 10:56 AMRachel D
08/06/2023, 10:59 AMCraig100
08/06/2023, 11:00 AMpublic void ConfigureServices(IServiceCollection services)
{
services.AddUmbraco(_env, _config)
.AddBackOffice()
.AddWebsite()
.AddSlimsy()
.AddComposers()
.Build();
services.AddTransient<Helpers>();
}
Craig100
08/06/2023, 11:03 AMRachel D
08/06/2023, 11:03 AMDan 'Diplo' Booth
08/06/2023, 6:37 PM