是否可以从控制器或管理器类中添加服务,而不是ConfigureService方法 [英] Is it possible to add a service from a controller or manager class other than the ConfigureService method

查看:52
本文介绍了是否可以从控制器或管理器类中添加服务,而不是ConfigureService方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要使用

services.AddPredictionEnginePool<..>

当我使用"IServiceCollection DI"时,我在下面收到通知

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

无法实例化服务类型"Microsoft.Extensions.DependencyInjection.IServiceCollection"的实现类型"Microsoft.Extensions.DependencyInjection.IServiceCollection".

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

我该如何使用;

services.AddPredictionEnginePool<..>

来自其他班级.

我为什么要这样做;

使用该服务的原因是在运行时添加一个新对象.

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

推荐答案

IServiceCollection 是DI容器的配置;您不应该在运行时使用它.最多只能使用 IServiceProvider (将其用作服务定位器),但是在使用DI时也可以将其视为反模式.

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

这篇关于是否可以从控制器或管理器类中添加服务,而不是ConfigureService方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆