ASP.NET Core 的 DI 容器是否保证服务的顺序? [英] Does ASP.NET Core's DI container assures order of services?
问题描述
当我用同一个接口向DI容器注册多个服务,然后请求一个IEnumerable
时,容器是否保证注册的顺序就是集合的顺序?因为这似乎是行为,但我在文档中找不到任何关于它的信息.
When I register multiple services to the DI container with the same interface and then request an IEnumerable<IService>
, do the container guarantee that the order of registration will be the order of the collection? because this seems to be the behavior but I couldn't find anything about it in the documentation.
示例 - 假设我们有这个接口:
Example - let's say we have this interface:
public interface IStep
{
void Execute();
}
还有一些实现:
public class FirstStep : IStep { ... }
public class SecondStep : IStep { ... }
public class ThirdStep : IStep { ... }
...
然后我们将它们注册到容器中:
And we register them to the container:
services.AddTransient<IStep, FirstStep>();
services.AddTransient<IStep, SecondStep>();
services.AddTransient<IStep, ThirdStep>();
最后请求IStep
的集合:
public class Plan
{
private readonly IEnumerable<IStep> steps;
public Plan(IEnumerable<IStep> steps)
{
this.steps = steps;
}
public void Execute()
{
foreach (var step in steps)
{
step.Execute();
}
}
}
假设步骤将按照注册顺序执行是否可以?如果不是,那么实现类似管道行为的最佳方法是什么?
Is it okay to assume that the steps will be executed according to the order of registration? If not, what will be the best way to implement a similar pipeline behavior?
推荐答案
是的.订单以注册订单为准,有保障
Yes it does. The order is based on registration order and is guaranteed
这篇关于ASP.NET Core 的 DI 容器是否保证服务的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!