简体   繁体   中英

ASP.Net Core Get Services From DI Container

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);
        }
    }
}

After much trial end error I came upon a solution, so I must do the answer my own question of shame. The solution turned out to be quite simple yet not very intuitive. The key is to call BuildServiceProvider().GetServices() on the ServiceCollection:

public class EventContainer : IEventDispatcher
{
    private readonly IServiceCollection _serviceCollection;

    public EventContainer(IServiceCollection serviceCollection)
    {
        _serviceCollection = serviceCollection;
    }

    public void Dispatch<TEvent>(TEvent eventToDispatch) where TEvent : IDomainEvent
    {
        var services = _serviceCollection.BuildServiceProvider().GetServices<IDomainHandler<TEvent>>();

        foreach (var handler in services)
        {
            handler.Handle(eventToDispatch);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM