简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM