如何使用.NET核心中的类型工厂解析服务数组?

时间:2017-10-14 02:33:23

标签: dependency-injection coreclr

在.NET核心2.0中是否可以注册T的多个服务并通过自定义工厂按需解决所有这些服务?

services.AddTransient<ISerivce, Service1>();
services.AddTransient<ISerivce, Service2>();
services.AddTransient<ISerivce, Service3>();


var services = myTypedFactory.ResolveAll();
myCustomFactory.Release(services);

这在Castle Windsor的日子里通过Typed Factory工具非常可行,但不确定如何在.NET核心中实现类似的功能。这将有助于减轻将DI带入一个不是从头开始构建的应用程序的负担.I ..

1 个答案:

答案 0 :(得分:2)

Startup.cs

中提供多个注册
public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IService, ServiceA>();
    services.AddTransient<IService, ServiceB>();
    services.AddTransient<IService, ServiceC>();
}

您应该能够依赖于依赖服务中的IEnumerable<TService>

public Foo(IEnumerable<IService> services)
{
    this.services = services;
}

这似乎不是documented yet,尽管奇怪的是,相反行为被记录为TryAdd*方法。