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?
Sitecore Stack Exchange is a question and answer site for developers and end users of the Sitecore CMS and multichannel marketing software. It only takes a minute to sign up.
Sign up to join this communityHow 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?
With Microsoft DI, the Scoped
lifetime will default to a request scope in ASP.NET.
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.
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.
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.