3

How can I register a service with "PerWebRequest" lifetime using the native Sitecore DI?

I can imagine I need to play around the Scoped lifetime and set the default scope to Web Request somehow? Did anyone try to do that?

2 Answers 2

4

The default scope

With Microsoft DI, the Scoped lifetime will default to a request scope in ASP.NET.

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection#service-lifetimes-and-registration-options

Scoped

Scoped lifetime services are created once per request.

...

Scoped objects are the same within a request, but different across different requests

Sitecore reinforces this behavior in a custom HTTP module defined in the Web.config:

<add type="Sitecore.DependencyInjection.SitecorePerRequestScopeModule, Sitecore.Kernel" name="SitecorePerRequestScopeModule" />

So the biggest scope in Sitecore is a request scope. That is the scope used by Sitecore.DependencyInjection.ServiceLocator and by Scoped services injected into your controllers and processors.

Custom scopes

If you wish, you can manually define smaller scopes:

using Microsoft.Extensions.DependencyInjection;
using Sitecore.DependencyInjection;

// ...

IServiceScopeFactory scopeFactory =
    ServiceLocator.ServiceProvider.GetService<IServiceScopeFactory>();

using (IServiceScope scope = scopeFactory.CreateScope())
{
    // request and use services here using scope.ServiceProvider
    ISomeContract service = scope.ServiceProvider.GetService<ISomeContract>();
}

The IDisposable.Dispose() method ends the scope lifetime. Once Dispose() is called, any scoped services that have been resolved from scope.ServiceProvider will be disposed.

0

the answer above is abount correct. I also figured out that Sitecore 8.2 adds default hanhdel for request scope.

<add type="Sitecore.DependencyInjection.SitecorePerRequestScopeModule, Sitecore.Kernel" name="SitecorePerRequestScopeModule" />

There is also the registration in the container for the scope:

Sitecore.DependencyInjection.ISitecoreServiceLocatorScope, Sitecore.Kernel

I believe replaing that registration we can set our custom scope.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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