【发布时间】:2017-03-13 01:49:21
【问题描述】:
我正在使用IServiceCollection 为我的对象创建所需服务的列表。现在我想实例化一个对象并让 DI 容器解析该对象的依赖关系
示例
// In my services config.
services
.AddTransient<IMyService, MyServiceImpl>();
// the object I want to create.
class SomeObject
{
public SomeObject(IMyService service)
{
...
}
}
如何让 DI 容器创建 SomeObject 类型的对象,并注入依赖项? (大概这就是它对控制器的作用?)
注意:我不想将SomeObject 存储在服务集合中,我只想能够做这样的事情......
SomeObject obj = startup.ServiceProvider.Resolve<SomeObject>();
... 基本原理:我不必将所有控制器都添加到服务容器中,所以我不明白为什么还要向它添加 SomeObject!?
【问题讨论】:
-
您想在哪里/如何创建对象?
-
@Nkosi 在控制台应用程序的 Main 方法中......类似于 SomeObject x = startup.ServiceProvider.ResolveDependenciesFor
(); -
Rationale: I don't have to add all of my controllers to the service container, so I don't see why I would have to add SomeObject to it either框架正在为你做这件事。它使用约定并为您注册所有控制器
标签: c# dependency-injection .net-core