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

查看:137
本文介绍了升级到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,它是作用域的,并且是根据请求创建的.

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天全站免登陆