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<>();
}
}
}
IServiceProvider.CreateScope
will resolveIServiceScopeFactory
and callCreateScope
on it. So functionally both methods are identical, since one calls the other. – EvkIHostedService/BackgroundService
which requires it's own scope separate from ASP.NET default. It would be just a single injection of the Service and all dependencies would be resolved from the registrations inStartUp.cs
. I was struggling with injecting theApplicationDbContext
(scoped going into singleton = exception). Solved this by going with registring a singleton contextFactory. Any thoughts on that approach? Is it right? – Connie King