I'm working with an ASP.Net Core Web application and using the typical registration method in the Startup.cs class to register my services.
I have a need to access the registered services in the IServiceCollection in order to iterate over them to find a particular service instance.
How can this be done with the ASP.Net Core DI container? I need to do this outside of a controller.
Below is an example of what I'm trying to do. Note that the All method does not exist on the ServiceCollection, that's what I'm trying to figure out:
public class EventContainer : IEventDispatcher
{
private readonly IServiceCollection _serviceCollection;
public EventContainer(IServiceCollection serviceCollection)
{
_serviceCollection = serviceCollection;
}
public void Dispatch<TEvent>(TEvent eventToDispatch) where TEvent : IDomainEvent
{
foreach (var handler in _serviceCollection.All<IDomainHandler<TEvent>>())
{
handler.Handle(eventToDispatch);
}
}
}
IServiceCollectionin the constructor ofEventContainerby registering it in your DI container? - larsbe