asp.net-core - 如何在 IServiceCollection.Configure() 中使用 IServiceProvider

标签 asp.net-core dependency-injection .net-core

是否可以使用IServiceProvider里面IServiceCollection.Configure()

我发现 Configure() 上没有过载接受类似 Func<IServiceProvider, T 的内容>。其他扩展方法,如IServiceCollection.AddScoped()有一个接受 Func<IServiceProvider, T> 的重载.

我想做这样的事情:

public static void AddCommandHandlers(this IServiceCollection services, Assembly assembly)
{
    // CommandExecutor has a dependency on CommandHandlerFactory
    services.AddScoped<CommandExecutor>();

    services.Configure<CommandHandlerFactory>(myFactory =>
    {
        // How can I use IServiceProvider here? Example scenario:

        foreach(Type t in FindHandlers(assembly))
            myFactory.AddHandler(serviceProvider => serviceProvider.GetService(t));
    });
}

目标是能够调用AddCommandHandlers对于不同的程序集多次扩展方法,并将找到的处理程序(使用 DI)附加到同一个 CommandHandlerFactory ,这样 CommandExecutor只需调用工厂即可获取处理程序。

或者也许还有其他方法?

感谢任何帮助。
谢谢。

最佳答案

您可以随时调用 IServiceCollection 上的 BuildServiceProvider() 扩展方法来构建 ServiceProvider。你需要 Microsoft.Extensions.DependencyInjection

它显然只包含已添加到集合中的任何服务,因此您需要以正确的顺序调用事物。

IServiceProvider sp = services.BuildServiceProvider();

关于asp.net-core - 如何在 IServiceCollection.Configure() 中使用 IServiceProvider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48751784/

相关文章:

azure - 生产 Web API 托管、容器 Web 应用程序或 Azure 容器实例?

c# - 从没有承载前缀的授权 header 中获取访问 token

c# - .NET Core - 全局化和本地化 - 类库

c# - IdentityServer4发现文档返回404

c# - 在 HttpClient.SendAsync() 之后无法访问已处置的对象

java - Spring如何执行方法

asp.net-mvc - 我的 View 模型应该以我的域实体为洋葱架构的核心吗?

java - Spring Autowiring 类

c# - 如何在 .Net Core Web API 项目中对使用 Mapper 的方法进行单元测试

c# - ASP.NET Core 2.1 区域路由不起作用