升级到 ASP.NET Core 2.0 后,无法从单例 IActiveUsersService 使用范围服务 IMongoDbContext [英] Cannot consume scoped service IMongoDbContext from singleton IActiveUsersService after upgrade to ASP.NET Core 2.0

查看:30
本文介绍了升级到 ASP.NET Core 2.0 后,无法从单例 IActiveUsersService 使用范围服务 IMongoDbContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天将一个项目更新到 ASP.NET Core 2,但出现以下错误:

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

无法使用来自单例 IActiveUsersService 的范围服务 IMongoDbContext

Cannot consume scoped service IMongoDbContext from singleton IActiveUsersService

我有以下注册:

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)
   {
      ...
   }
}

为什么DI不能消费服务?对于 ASP.NET Core 1.1,一切正常.

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

推荐答案

您不能使用生命周期较短的服务.作用域服务仅针对每个请求存在,而单例服务创建一次并共享实例.

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.

现在应用中只存在 IActiveUsersService 的一个实例.但是它想要依赖 MongoDbContext,它是 Scoped,并且是按请求创建的.

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.

您必须:

  1. 使 MongoDbContext 成为单例,或
  2. 使 IActiveUsersService 成为作用域,或
  3. MongoDbContext 作为函数参数传入用户服务
  1. Make MongoDbContext a Singleton, or
  2. Make IActiveUsersService Scoped, or
  3. Pass MongoDbContext into the user service as a function argument

这篇关于升级到 ASP.NET Core 2.0 后,无法从单例 IActiveUsersService 使用范围服务 IMongoDbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆