在下面的代码中,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
之前注册被调用所以它不应该解析为单例吗?
最佳答案
您在注册 DocumentDbConnection
之前构建服务提供者。您应该首先注册您需要的服务。然后 BuildServiceProvider
将使用之前注册的服务构建一个服务提供者:
services.AddSingleton<DocumentDbConnection>(x => new DocumentDbConnection(uri, authKey));
var serviceProvider = services.BuildServiceProvider();
// code using serviceProvider
关于c# - ASP.NET 5 MVC 6 DI : ServiceProvider not resolving type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32584695/