How is a Scoped service instance handled in a .NET Core Console application?

When you build IServiceProvider from IServiceCollection (BuildServiceProvider method) and you use this instance of IServiceProvider to resolve IDbConnection you will get same instance of IDbConnection every time. Scope is connected to IServiceProvider. to create new scope you need to resolve from the container IServiceScopeFactory and use it to create IServiceProvider that is scoped:

using (var scope = scopeFactory.CreateScope())
{
   var scopedConnection = scope.ServiceProvider.GetRequiredService<IDbConnection>();      
}

Connection will be disposed when scope is disposed.

In ASP Core scopes are managed for you by middleware which creates new scope and then uses IServiceProvider attached to this scope to resolve Controller and everything within this web request. In console application you need to manage scopes yourself.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)