2

To get the url of an item we can do it via LinkManager:

var url1 = LinkManager.GetItemUrl(item);

can even provide UrlOptions on it:

 var url2 = LinkManager.GetItemUrl(item, new UrlOptions() { LanguageLocation = LanguageLocation.FilePath });

But, LinkProvider can do it too:

 var linkProvider = new LinkProvider();
                    var url4 = linkProvider.GetItemUrl(item, new UrlOptions() { LanguageLocation = LanguageLocation.FilePath });

What is the difference between them and for best practice, what should we use?

0

As best practice for generating a link always use LinkManager.

A LinkProvider is the means by which Sitecore generates URLs for items, it is provider for LinkManager.

Don't generate link using LinkProvider class.

You can add your custom LinkProvider to generate customize links using LinkManager.

This can be useful when you have multiple sites that all have different link requirements. For example, if you want the language in the URL on multilingual sites and not on a single language site. To work with a custom link provider, you can add providers to the linkManager config section.

To add and select a link provider:

Create a new patch file. Make sure to add your own <add/> node to the providers node under the linkManager node and add the code for your custom provider.

For example:

<linkManager defaultProvider="sitecore">
<providers>
<add name="customLinkProvider" type="Sitecore.XA.Foundation.Multisite.LinkManagers.LocalizableLinkProvider, Sitecore.XA.Foundation.Multisite" cacheExpiration="5" addAspxExtension="false" alwaysIncludeServerUrl="false" encodeNames="true" languageEmbedding="always" languageLocation="filePath" shortenUrls="true" useDisplayName="false"/>
</providers>
</linkManager>

Reference: https://doc.sitecore.com/developers/sxa/19/sitecore-experience-accelerator/en/add-and-select-a-custom-link-provider.html

0

If you use the LinkManager Sitecore will fetch the current LinkProvider and use that one. If you create a LinkProvider yourself, you will get a new one with default settings.

Best approach: you should use the LinkManager in order to start with the correct LinkProvider for the current context.

Although you can set some options on the provider, there could be other customizations that you skip if you take a new LinkProvider and you might end up with different results. Even if the result now looks the same, go for the Manager approach for future consistency.

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.