在ConfigureServices()我的应用程序的引导过程中,我使用 .Net Core 附带的依赖注入框架注册了大部分瞬态和作用域类型。但是,我确实有一种注册为单例的类型是我的InProcessBus(我使用的是 CQRS 风格的架构)。
services.AddSingleton<InProcessBus>(new InProcessBus());
...
services.AddSingleton<ICommandSender>(y => y.GetService<InProcessBus>());
services.AddSingleton<IEventPublisher>(y => y.GetService<InProcessBus>());
Run Code Online (Sandbox Code Playgroud)
如您所见,我正在为将在 API 的控制器中使用的实际类型使用实现工厂函数。真正奇怪的是,当控制器加载并且运行时尝试构造函数注入时,ICommandSender它无法解决它并报告错误。
如果我检查serviceCollection我可以看到 implementationFactory 已针对ImplementationInstance属性下的类型正确注册。
在Startup类的ConfigureServices()方法末尾深入和直接解析类型确认容器正在解析null.
ServiceLocator.GetService<ICommandSender>() // Is Null
Run Code Online (Sandbox Code Playgroud)
为什么针对明显存在于容器中的单例的 ImplementationFactory 方法不会在运行时解析?
.net dependency-injection asp.net-core-mvc .net-core asp.net-core