Skip to content

What is the best practice to get scoped service from singletone service #10686

Answered by jtkech
HengzheLi asked this question in Q&A
Discussion options

You must be logged in to vote

If you are sure that your method is called in a scope context

using Microsoft.Extensions.DependencyInjection;
using OrchardCore.Environment.Shell.Scope;

        var service = ShellScope.Services.GetRequiredService<IService>();

In a more aspnetcore way you can inject IHttpContextAccessor to retrieve the current RequestServices. A request context is not the same as a scope context (here the scope of a given tenant / shell) but we take care in a given request that RequestServices is set to the scope service provider of the tenant / shell on which the request was done.

Otherwise if the method is not called in a scope context you should create a scope by using GetScopeAsync(), notice that in…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by HengzheLi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants