user348173 user348173 - 28 days ago 136
C# Question

ASP.NET Core 2: Cannot consume scoped service IMongoDbContext from singleton IActiveUsersService

I updated a project to ASP.NET Core 2 today and I get the following error:


Cannot consume scoped service IMongoDbContext from singleton IActiveUsersService


I have the following registration:

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 IActiveUsersService: ActiveUsersService
{

public IActiveUsersService(IMongoDbContext mongoDbContext)
{
...
}
}


Why DI can't consume the service? All works fine for ASP.NET Core 1.1.

Answer Source

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:

a: Make MongoDbContext a Singleton

or

b: Make IActiveUsersService Scoped