问题描述
我今天将项目更新为ASP.NET Core 2,并且出现以下错误:
I updated a project to ASP.NET Core 2 today and I get the following error:
我有以下注册:
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.
您将必须:
- 使
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!