C# 如果是ImplementedInterface,解析如何工作?

C# 如果是ImplementedInterface,解析如何工作?,c#,autofac,C#,Autofac,我有一个简单的应用程序,如下所示: public interface PaymentProcessor { void ProcessPayment(); } public class PaymentProcessorOne : PaymentProcessor { public void ProcessPayment() { Console.WriteLine("Payment processed by PaymentProcessorOne.");

我有一个简单的应用程序,如下所示:

public interface PaymentProcessor
{
    void ProcessPayment();
}

public class PaymentProcessorOne : PaymentProcessor
{
    public void ProcessPayment()
    {
        Console.WriteLine("Payment processed by PaymentProcessorOne.");
    }
}

public class PaymentProcessorTwo : PaymentProcessor
{
    public void ProcessPayment()
    {
        Console.WriteLine("Payment processed by PaymentProcessorTwo.");
    }
}

public class PaymentProcessorThree : PaymentProcessor
{
    public void ProcessPayment()
    {
        Console.WriteLine("Payment processed by PaymentProcessorThree.");
    }
}
我在Program.cs中将我的类型注册为:

    var builder = new ContainerBuilder();
    builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces();

    IContainer container = builder.Build();
    var processor = container.Resolve<PaymentProcessor>();
    processor.ProcessPayment();
var builder=newcontainerbuilder();
RegisterAssemblyTypes(Assembly.GetExecutionGassembly()).AsImplementedInterfaces();
IContainer容器=builder.Build();
var processor=container.Resolve();
processor.ProcessPayment();
我第一次执行这段代码时,输出是“PaymentProcessorTwo处理的付款”。然而,当我在不同的机器上执行相同的代码时,输出是“PaymentProcessorTree处理的付款”


我想知道autofac是如何解决主逻辑中的
支付处理器的问题的。

问题不在
AsImplementedInterfaces()
,而在
.registerasemblytypes()

当为接口注册了多个类型时,解析类型的魔力非常简单——最后一次注册获胜。这意味着,当您使用
RegisterAssemblyTypes()
时,类型的顺序是未知的,并且在运行代码的不同机器上可能会有所不同


有几种方法可以使其按预期工作,例如,在将类型传递给
RegisterAssemblyTypes()
method

之前,您可以显式注册类型或以某种方式对其进行排序。您需要的行为是什么?您是否始终希望有一个特定的实现?相关:是的,我希望
processor
始终有一个
PaymentProcessorOne
的实例。