ASP.NET Core 的 DI 容器是否保证服务的顺序?

Gur*_*ler 2 c# dependency-injection .net-core asp.net-core

当我用同一个接口向DI容器注册多个服务然后请求一个时IEnumerable<IService>,容器是否保证注册的顺序就是集合的顺序?因为这似乎是行为,但我在文档中找不到任何关于它的信息。

示例 - 假设我们有这个接口:

public interface IStep
{
    void Execute();
}
Run Code Online (Sandbox Code Playgroud)

以及一些实现:

public class FirstStep : IStep { ... }
public class SecondStep : IStep { ... }
public class ThirdStep : IStep { ... }
...
Run Code Online (Sandbox Code Playgroud)

我们将它们注册到容器中:

services.AddTransient<IStep, FirstStep>();
services.AddTransient<IStep, SecondStep>();
services.AddTransient<IStep, ThirdStep>();
Run Code Online (Sandbox Code Playgroud)

最后请求一个集合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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

假设步骤将根据注册顺序执行是否可以?如果不是,那么实现类似管道行为的最佳方法是什么?

dav*_*owl 5

是的,它确实。订单以注册订单为准,有保障

  • 您介意引用并指出官方文档中的声明吗? (5认同)
  • @Steven我认为该行为已记录在[此处](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1#service-registration-methods)。 (3认同)