【发布时间】:2018-01-30 08:09:08
【问题描述】:
我今天将一个项目更新为 ASP.NET Core 2,但出现以下错误:
无法使用单例 IActiveUsersService 中的作用域服务 IMongoDbContext
我有以下注册:
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 一切正常。
【问题讨论】:
-
你为什么一开始就想让 Mongo 上下文成为范围?您是否具有某种租户功能,仅在运行时才知道租户 ID? MongoDatabase 是线程安全的,因此您也可以将其保留为单例(假设您没有运行 100 个它保持打开许多连接)。另一方面,EF Core 不是线程安全的,并且默认情况下具有缓存机制(EF Core 跟踪也充当缓存),因此很自然地将其设置为范围)
标签: c# asp.net-core