My understanding is that when using the built in the dependency injection, a .NET Core console app will require you to create and manage all scopes yourself whereas a ASP.NET Core app will create and manage the HttpRequest
scope by default through defined middleware(s).
With ASP.NET Core, you can optionally create and manage your own scopes that by calling CreateScope()
for when you need services that live outside of a HttpRequest
.
It is clear that calling IServiceScopeFactory.CreateScope()
will create a new IServiceScope
every time; however, does calling the IServiceProvider.CreateScope()
extension method also create a new IServiceScope
every time?
Basically, is there a meaningful difference between the following ways to create scope in both ASP.NET Core and .NET Core console apps:
public class Foo()
{
public Foo(IServiceProvider serviceProvider)
{
using(var scope = serviceProvider.CreateScope())
{
scope.ServiceProvider.GetServices<>();
}
}
}
and
public class Bar()
{
public Bar(IServiceScopeFactory scopeFactory)
{
using(var scope = scopeFactory.CreateScope())
{
scope.ServiceProvider.GetServices<>();
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…