3

Scenario

A page contains several separate renderings. Each rendering displays some data which is returned from a remote service. Several of these data items come from the same remote service.

This leads to that service being requested multiple times per page load, which seems inefficient.

Separate renderings are desirable as they can be used elsewhere on the website, and provides content editors flexibility.

Solutions

Does an established pattern exist to handle this scenario in an efficient way?

5

Register the service in your DI scoped for the request.

When the first component calls the service, save the value in the service.

When next component wants the same data, the service will already have it.

I used this blog post as a guide how to:

https://www.coreysmith.co/sitecore-dependency-injection-scoped-services/

In shortcut - register service:

public class ExampleConfigurator : IServicesConfigurator
{
    public void Configure(IServiceCollection serviceCollection)
    {
        serviceCollection.AddScoped<IScopedService, ScopedService>();
    }
}

And the service itself:

public class ScopedService : IScopedService
{
    private object _externalData;
    public object ExternalData
    {
        get { return _externalData ?? (_externalData = GetDataFromExternalProvider()); }
    }
}

And register the configurator:

<configuration>
    <sitecore>
        <services>
            <configurator type= "ExampleConfigurator, MyAssembly"/>
        </services>
    </sitecore>
<configuration>

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.