问题描述
我今天将一个项目更新到 ASP.NET Core 2,但出现以下错误:
I updated a project to ASP.NET Core 2 today and I get the following error:
无法使用来自单例 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,一切正常.
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.
您必须:
- 使
MongoDbContext
成为单例,或 - 使
IActiveUsersService
成为作用域,或 - 将
MongoDbContext
作为函数参数传入用户服务
- Make
MongoDbContext
a Singleton, or - Make
IActiveUsersService
Scoped, or - Pass
MongoDbContext
into the user service as a function argument
这篇关于升级到 ASP.NET Core 2.0 后,无法从单例 IActiveUsersService 使用范围服务 IMongoDbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!