在下面的代码中,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));
}
为什么会这样?该类型是在调用GetService
之前注册的,所以如果不解析为单例?
答案 0 :(得分:12)
您在注册DocumentDbConnection
之前构建服务提供商。您应该首先注册您需要的服务。然后BuildServiceProvider
将构建一个服务提供商,其服务已注册到那时:
services.AddSingleton<DocumentDbConnection>(x => new DocumentDbConnection(uri, authKey));
var serviceProvider = services.BuildServiceProvider();
// code using serviceProvider