Does ASP.NET Core's DI container assures order of services?

旧巷老猫 提交于 2020-04-06 19:03:09

问题


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();
}

And some implementations:

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>();

And finally request a collection of 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?


回答1:


Yes it does. The order is based on registration order and is guaranteed




回答2:


Yes they execute in order, read more: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1

EDIT: More specific link: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/startup?view=aspnetcore-3.1#extend-startup-with-startup-filters

Thanks to @Sai Puli



来源:https://stackoverflow.com/questions/60566047/does-asp-net-cores-di-container-assures-order-of-services

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!