1

I have a simple application as shown below:

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.");
    }
}

And I'm registering my types in Program.cs as:

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

    IContainer container = builder.Build();
    var processor = container.Resolve<PaymentProcessor>();
    processor.ProcessPayment();

First time when I executed this code, the output was "Payment processed by PaymentProcessorTwo". However, when I executed the same code on a different machine the output was "Payment processed by PaymentProcessorThree".

I would like to know how is autofac resolving the PaymentProcessor in the main logic.

Maria Ines Parnisari
  • 16,584
  • 9
  • 85
  • 130
Gaurav Gahlot
  • 1,583
  • 3
  • 14
  • 19

1 Answers1

1

The problem is not in AsImplementedInterfaces(), but in .RegisterAssemblyTypes().

The magic of resolving types, when there are more than one type registered for interface is pretty simple - last registration wins. It means, the order of types is unknown when you use RegisterAssemblyTypes(), and can vary on different machines you run your code.

There are several ways to o make it work as expected, e.g. you can explicitly register your types or sort them somehow before you pass them to RegisterAssemblyTypes() method

tdragon
  • 3,209
  • 1
  • 16
  • 17