Is it possible to add a service from a controller or manager class other than the ConfigureService method

生来就可爱ヽ(ⅴ<●) 提交于 2021-01-29 17:31:05

问题


I want to Use

services.AddPredictionEnginePool<..>

When I use "IServiceCollection DI" I receive the notification below

Cannot instantiate implementation type 'Microsoft.Extensions.DependencyInjection.IServiceCollection' for service type 'Microsoft.Extensions.DependencyInjection.IServiceCollection'.

How can I Use this;

services.AddPredictionEnginePool<..>

From other classes.

Why I want do;

The reason of the usage of the service is to add a new object in runtime.


回答1:


IServiceCollection is the configuration of the DI container; you're not supposed to used it at runtime. At most, one would use IServiceProvider (using it as a Service Locator), but that can also be seen as an anti-pattern when using DI.

Without more context on the exact thing you're trying to accomplish, I'd suggest using some sort of factory class that knows how the create those objects at runtime (based on some data/config), and inject the factory where needed.

https://www.martinfowler.com/articles/injection.html



来源:https://stackoverflow.com/questions/63736588/is-it-possible-to-add-a-service-from-a-controller-or-manager-class-other-than-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!