简体   繁体   中英

Asp.net core service per request scope in child scopes

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM