【发布时间】:2019-06-23 15:20:31
【问题描述】:
我有一个奇怪的情况。我在启动类中注册了我的服务,就像这样
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSingleton<ISearchService, SearchService>();
services.AddSingleton<IBrandSearchService, BrandSearchService>();
services.AddSingleton<INearbySearchService, NearbySearchService>();
services.AddSingleton<ILocationService, LocationService>();
...
}
但是当我尝试在控制器的构造函数中访问它们时,它们为空,即使我将它添加到构造函数参数中,或者尝试从 ServiceCollection 中获取
public class SuggestController
{
readonly ILocationService locationService;
public SuggestController(IOptions<SiteSettings> settings, IOptions<DBAccessBuilder> access, IStringLocalizer<SharedResources> localizer, IMemoryCache memoryCache, IHostingEnvironment environment)
{
this.locationService = (ILocationService)new ServiceCollection().BuildServiceProvider().GetService(typeof(ILocationService));
}
}
实现 ILocationService 接口的 My Location 类
public class LocationService : ILocationService
{
readonly ISolrOperations<LocationResult> search;
...
public LocationService(ISolrOperations<LocationResult> search)
{
this.search = search;
}
...
}
我错过了什么?
【问题讨论】:
-
你正在创建一个全新的
ServiceCollection实例,它是empty,然后用它来尝试获取一个已经用不同IServiceCollection。为什么不直接将ILocationService参数带入SuggestController构造函数? -
我以前就是这么做的。如果这样做,我会得到 InvalidOperationException: Unable to resolve service for type 'SolrNet.ISolrOperations`1[LocationResult]' 同时尝试激活 'LocationService'。
-
那只是因为你还没有在 DI 注册
ISolrOperations<LocationResult>。 -
@KirkLarkin 可能是他没有赶上事情。如果您将其作为完整答案发布,那就太好了。
标签: c# asp.net-core dependency-injection interface .net-core