FromKeyedServices returns null when used in primary constructors

Today I discovered that, when using NET 8 and a service with primary constructor, the FromKeyedServicesAttribute does nothing (I assume). Perhaps the attribute is magically removed when the code is compiled.

I guess that

public class PaymentService(
    IPaymentProvider defaultPaymentProvider
    ) : IPaymentService
{ }Code language: C# (cs)

is changed to

public class PaymentService : IPaymentService
   public PaymentService(IPaymentProvider defaultPaymentProvider) 
   { }
}Code language: C# (cs)

on compile (note the missing attribute!)

Changing from primary constructor to an ordinary constructor with no other change made the code work as intended.


Leave a Reply

Your email address will not be published. Required fields are marked *