ASP.NET Core的DI容器是否确保服务顺序? [英] Does ASP.NET Core's DI container assures order of services?

查看:104
本文介绍了ASP.NET Core的DI容器是否确保服务顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用相同的接口向DI容器注册多个服务,然后请求 IEnumerable< IService> 时,请确保容器的注册顺序为收集顺序?因为这似乎是行为,但我在文档中找不到任何内容。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆