Cannot consume scoped service IMongoDbContext from singleton IActiveUsersService after upgrade to ASP.NET Core 2.0
You can't use a service with a smaller lifetime. Scoped services only exist per-request, while singleton services are created once and the instance is shared.
Now only one instance of IActiveUsersService
exists in the app. But it wants to depend on MongoDbContext
, which is Scoped, and is created per-request.
You will have to either:
- Make
MongoDbContext
a Singleton, or - Make
IActiveUsersService
Scoped, or - Pass
MongoDbContext
into the user service as a function argument
There are important differences between Scoped and Singleton services. The warning is there to bring this to light, and turning it off or switching around lifetimes indiscriminately to make it go away won't solve the problem.
Scoped services are created from an IServiceScope
. One of its most important purposes is to ensure that any IDisposable
services which are created in that scope are properly disposed when the scope itself is.
In ASP.NET Core, a service scope is automatically created for you on each incoming request, so you ordinarily don't need to worry about this. However, you can also create your own service scope; you just need to dispose of it yourself.
One way to do this is to:
- make your singleton service
IDisposable
, - inject
IServiceProvider
, - create and store an
IServiceScope
scope using theIServiceProvider.CreateScope()
extension method, - use that scope to create the the scoped service you need,
- dispose the service scope in the
Dispose
method.
services.AddSingleton<IActiveUsersService, ActiveUsersService>();
services.AddScoped<IMongoDbContext, MongoDbContext>();
services.AddSingleton(option =>
{
var client = new MongoClient(MongoConnectionString.Settings);
return client.GetDatabase(MongoConnectionString.Database);
})
public class MongoDbContext : IMongoDbContext
{
private readonly IMongoDatabase _database;
public MongoDbContext(IMongoDatabase database)
{
_database = database;
}
public IMongoCollection<T> GetCollection<T>() where T : Entity, new()
{
return _database.GetCollection<T>(new T().CollectionName);
}
}
public class ActiveUsersService: IActiveUsersService, IDisposable
{
private readonly IServiceScope _scope;
public ActiveUsersService(IServiceProvider services)
{
_scope = services.CreateScope(); // CreateScope is in Microsoft.Extensions.DependencyInjection
}
public IEnumerable<Foo> GetFooData()
{
using (var context = _scope.ServiceProvider.GetRequiredService<IMongoDbContext>())
{
return context.GetCollection<Foo>();
}
}
public void Dispose()
{
_scope?.Dispose();
}
}
Depending on how you're using these and the scoped services you're consuming, you could instead do one of the following:
- create a single instance of the scoped service and use it for the life of the singleton; or
- store a reference to the (injected) root
IServiceProvider
, use it to create a newIServiceScope
inside ausing
block every time you need a scoped service, and let the scope get disposed when the block exits.
Just keep in mind that any IDisposable
services created from an IServiceScope
will get automatically disposed when the scope itself does.
In short, don't just change around the lifetimes of your services to "make it work"; you still need to think about those and be sure they get disposed properly. ASP.NET Core handles the most common cases automatically; for others, you just need to do a bit more work.
Ever since C# 1.0 we have had using()
blocks to ensure resources are disposed correctly. But using()
blocks don't work when something else (the DI service) is creating those resources for you. That's where Scoped services come in, and using them incorrectly will lead to resource leaks in your program.
You can also add
.UseDefaultServiceProvider(options =>
options.ValidateScopes = false)
before .Build()
in Program.cs
file to disable the validation.
Try this only for development testing, ActiveUsersService is singleton and has a larger lifetime than MongoDbContext which is scoped and will not get disposed.
There is another way to approach this issue, and it is by adding the MongoDbContext
to the DI as AddTransient
like this:
services.AddSingleton<IActiveUsersService, ActiveUsersService>();
services.AddTransient<IMongoDbContext, MongoDbContext>();
The meaning of using this approach is that you'll end up with an instance of MongoDbContext
for each Singleton
class you have using it.
For example, if you have 10 Singleton classes using MongoDbContext
you'll have 10 instances of it, but it's instead of creating an instance for every request.
See this for reference: Cannot Consume Scoped Service From Singleton – A Lesson In ASP.net Core DI Scopes