I previously blogged about a Switching Link Provider for Sitecore, allowing you use a different LinkProvider for different sites.
There were a number of changes in Sitecore 8.2 to LinkManager/Provider as a result of the Dependency Injection changes, unfortunately one of them being the
Providers collection being marked
[Obsolete]. The code in the old post should still work, but you’ll get that annoying warning.
The previous code worked by creating a Link Provider which acted as a switcher that in turn called a different Provider. This was a hack because we could not switch out the Link Manager itself. Well the DI changes in Sitecore 8.2 allow us to do that instead and provide our own implementation of LinkManager instead.
Slightly annoyingly, the code could have been super simple if we were able to inherit the
Sitecore.Links.DefaultLinkManager and just override the
internal LinkProvider Provider… But notice it’s marked internal so we are left having to essentially copy/paste all the other properties (╯°□°）╯︵ ┻━┻
Anyway, we can replace the
LinkManager with our own implementation, which checks if a
linkProvider property is set on the context site node. If not, then the
defaultProvider that is set on the “ node is used. There is no need for an additional switching provider to set fallbacks.
|public class ServicesConfigurator : IServicesConfigurator|
|public void Configure(IServiceCollection serviceCollection)|
|var service = new ServiceDescriptor(typeof(BaseLinkManager), typeof(SwitchingLinkManager), ServiceLifetime.Singleton);|
|<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/">|
|<add name="custom-provider" type="Sitecore.Links.LinkProvider, Sitecore.Kernel"|
|<add name="alternate-provider" type="MySite.Custom.Links.AlternateProvider, MySite.Custom" … />|
|<add name="default-provider" type="MySite.Custom.Links.DefaultProvider, MySite.Custom" … />|
DI FTW. Enjoy.