Cannot consume scoped service IMongoDbContext from singleton IActiveUsersService after upgrade to ASP.NET Core 2.0

前端 未结 4 1163
粉色の甜心
粉色の甜心 2020-11-30 05:42

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

Cannot consume scoped service IMongoDbContext from singleton IActiveUsersSe

4条回答
  •  半阙折子戏
    2020-11-30 05:55

    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:

    1. Make MongoDbContext a Singleton, or
    2. Make IActiveUsersService Scoped, or
    3. Pass MongoDbContext into the user service as a function argument

提交回复
热议问题