The following code works in Sitecore 8.2 but not in Sitecore 9:
var provider = LinkManager.Provider;
The Provider
property is not available anymore in Sitecore 9 Sitecore.Kernel, what should I use instead?
Sitecore Stack Exchange is a question and answer site for developers and end users of the Sitecore CMS and multichannel marketing software. It only takes a minute to sign up.
Sign up to join this communityThe following code works in Sitecore 8.2 but not in Sitecore 9:
var provider = LinkManager.Provider;
The Provider
property is not available anymore in Sitecore 9 Sitecore.Kernel, what should I use instead?
After digging into the new Sitecore.Kernel assembly I have found the following way to get the default LinkProvider
or your custom with the following appraches:
To get default Sitecore.Links.LinkProvider
:
var defaultProvider = ServiceLocator.GetRequiredResetableService<ProviderHelper<Sitecore.Links.LinkProvider, LinkProviderCollection>>()?.Value?.Provider;
To get your custom YourNamespace.LinkProvider
:
var customProvider = ServiceLocator.GetRequiredResetableService<ProviderHelper<Sitecore.Links.LinkProvider, LinkProviderCollection>>()?.Value?.Provider as YourNamespace.LinkProvider;
As below in the comments Pete and Mark pointed out that the ServiceLocator
is an antipattern so I gave a try to do it with dependency injection, and it works. The following example shows, how you can use it with ItemResolver
and DI:
public class ItemResolver : HttpRequestProcessor
{
protected readonly ProviderHelper<Sitecore.Links.LinkProvider, LinkProviderCollection> providerHelper;
public ItemResolver(ProviderHelper<Sitecore.Links.LinkProvider, LinkProviderCollection> providerHelper)
{
this.providerHelper = providerHelper;
}
private Sitecore.Links.LinkProvider GetSitecoreLinkProvider()
{
return this.providerHelper?.Provider;
}
private YourNamespace.LinkProvider GetCustomLinkProvider()
{
return this.providerHelper?.Provider as YourNamespace.LinkProvider;
}
}
Configuration:
<pipelines>
<httpRequestBegin>
<processor type="YourNamespace.ItemResolver, YourNamespace" resolve="true" />
</httpRequestBegin>
</pipelines>