3

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?

3

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>
  • 2
    I want to upvote, but I think that you should provide the proper way to get this. While using ServiceProvider works, it's an antipattern to standard Dependency Injection, which should be used instead, but thats probably more of an opinion, but I consider it best practice. – Pete Navarra Dec 16 '18 at 20:55
  • I second that. Going via ServiceLocator cannot - I truly hope - be the new official way of getting to the LinkProvider – Mark Cassidy Dec 16 '18 at 21:13
  • @PeteNavarra so I could inject ProviderHelper<LinkProvider, LinkProviderCollection> via constructor? I will try to use DI and update the answer. – Tamás Tárnok Dec 16 '18 at 21:16
  • 1
    @PeteNavarra, it works like a charm with DI. Thanks for pointing this out! – Tamás Tárnok Dec 17 '18 at 7:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.