Dav*_*New 8 c# dependency-injection asp.net-core-mvc asp.net-core
在下面的代码中,serviceProvider.GetService<DocumentDbConnection>()解析为null:
public void ConfigureService(IServiceCollection services)
{
var serviceProvider = services.BuildServiceProvider();
services.AddSingleton<DocumentDbConnection>(
x => new DocumentDbConnection(uri, authKey));
// service is null?
var connection = serviceProvider.GetService<DocumentDbConnection>();
services.AddTransient<IStopRepository, StopRepository>(
x => new StopRepository(connection, databaseId, collectionId));
}
Run Code Online (Sandbox Code Playgroud)
为什么会这样?该类型在GetService被调用之前被注册,所以它不能解析为单例吗?
Hen*_*ema 12
您在注册之前正在构建服务提供商DocumentDbConnection.您应该首先注册您需要的服务.然后BuildServiceProvider将构建一个服务提供商,其服务已注册到那时:
services.AddSingleton<DocumentDbConnection>(x => new DocumentDbConnection(uri, authKey));
var serviceProvider = services.BuildServiceProvider();
// code using serviceProvider
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1888 次 |
| 最近记录: |