1

Is there any way to register service in asp.net core as Scoped to request not to current request scope?

public void ConfigureServices(IServiceCollection services)
{
  services.AddScoped<IMyService, MyService>();
}

After registration service is available in request scope, but as soon as I create new child scope:

var service1 = serviceProvider.GetService<IMyService>();
var scope = serviceProvider.CreateScope();
var service2 = scope.ServiceProvider.GetService<IMyService>();

Service1 and service2 are 2 instances. Even if child scope is created in the same request. Is there a way to register service to request scope so all child scopes created from the same request scope would have the same one instance?

malczu
  • 11
  • 2
  • You can solve this issue with always moving your Service Interfaces on the constructors and note that every passed object must be defined as a scoped in ServiceCollection, so just get instances from constructor. Use Constructor Injection always it will handles this kind of issues. – Mustafa Salih ASLIM Jun 22 '22 at 16:50
  • 1
    Lastly I have one question to be more clear, if we need a same scope why we need to use CreateScope() method right? so this method always creates new Scope not inner scope. more detail: https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.iservicescopefactory.createscope?view=dotnet-plat-ext-6.0 – Mustafa Salih ASLIM Jun 22 '22 at 16:55
  • @MustafaSalihASLIM imagine, that you have tenant object, you want to set it somewhere in the middleware when request starts. It should be request scoped, not scoped to the current container scope. So if you create new scope inside your code explicitly this new scope is still part of the same request, so you should have access to tenant for that request. In current asp.net core configuration as soon as you create new scope you loose your tenant even though it's still part of the same request. – malczu Jun 28 '22 at 07:43

1 Answers1

2

There is no RequestScope feature excipliy in .Net Core on the contrary .Net Framework. we use "Scoped", because .Net Core creates scope at the beggining of the first called middleware, inner services gets same instance of the object thanks to Constructor Injection. For Example; if you get an API request, that is "scoped request instance", It will carry on all instaces to inner scopes, but you can not do manually using CreateScope() method as I mentioned why you can't.

You confused about creating inner scope but .Net Core creates Scope for each API Requests.

Examples: https://stackoverflow.com/a/38139500/7575384