首页 文章

ASP.Net Core从DI Container获取服务

提问于
浏览
0

我正在使用ASP.Net Core Web应用程序并使用Startup.cs类中的典型注册方法来注册我的服务 .

我需要访问IServiceCollection中的已注册服务,以便迭代它们以查找特定的服务实例 .

如何使用ASP.Net Core DI容器完成这项工作?我需要在控制器外面这样做 .

以下是我正在尝试做的一个例子 . 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);
        }
    }
}

1 回答

  • 1

    在经历了多次试验结束错误之后,我找到了一个解决方案,所以我必须回答我自己的羞耻问题 . 解决方案结果非常简单但不太直观 . 关键是在ServiceCollection上调用BuildServiceProvider() . GetServices():

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

相关问题