是否可以使用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/