Cannot use IMONoDbContext with IActiveUsersService after upgrading to ASP.NET Core 2.0

I upgraded the project to ASP.NET Core 2 today and I received the following error:

Cannot use the restricted IMongoDbContext service 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 can't DI use this service? Everything works fine for ASP.NET Core 1.1.

+7
c # asp.net-core
source share
2 answers

You cannot use a service with a shorter lifespan. Limited services exist only for each request, and single-user services are created once and the instance is shared.

Now there is only one instance of IActiveUsersService in the application. But he wants to depend on MongoDbContext , which is the scope, and is created for each request.

You will have to either:

a: Make MongoDbContext a Singleton

or

b: Make IActiveUsersService available

+12
source share

You can also add

 .UseDefaultServiceProvider(options => options.ValidateScopes = false) 

to .Build() in the Program.cs file to disable validation.

Try this only for development testing, ActiveUsersService is singleton and has a longer life than MongoDbContext, which is limited and will not be removed.

0
source share

All Articles