Azure/azure-functions-dotnet-extensions

[Pls Help] Why DI doesn't work as expected when using Azure Function

tangdaowan opened this issue · 2 comments

When I use Azure Function to do some work, there comes a problem. Here are some details:

Please refer to the code snippet below. I am using denpendency injection to achieve Inversion of Control between classes and their dependencies. I have a class named MessagingEventGridPublisher with 2 constuctors, whose params are MessagingEventGridPublisher's dependencies. During function startup, I have DI this MessagingEventGridPublisher through services.AddSingleton<IEventGridPublisher, MessagingEventGridPublisher>(); . After I DI EventGridSecretOptions, I assume it will automatically resolve MessagingEventGridPublisher using the second constuctor. However it turns out I am wrong. It actually uses the first constructor to resolve MessagingEventGridPublisher. Do you know why it cannot be auto resolved as expected?

Besides, I want to call out that when using Azure Web APP, it works as expected.

public class MessagingEventGridPublisher : IEventGridPublisher
{
       public MessagingEventGridPublisher(EventGridManagedIdentityOptions options, TokenProvider tokenProvider, ILoggerX logger)
            : this(options, InitEventGridManagedIdentityClient(options, tokenProvider, logger), logger)
        {
        }

        public MessagingEventGridPublisher(EventGridSecretOptions options, ILoggerX logger)
            : this(options, InitEventGridSecretClient(options, logger), logger)
        {
        }
}

In general, having multiple public constructors is an anti-pattern when using DI. There's no way the DI framework can unambiguously decide which constructor to use. Why do you have the first constructor if you only use the second?

As @CasperWSchmidt multiple public ctors is an anti-pattern for DI. You will need to figure out how to specify which ctor to use (we use DryIoc, so see if there have a way to do that), manually register this service with a callback using the ctor you want, or remove the extra ctor.

Going to close this as it is a general DI question and not specific to the responsibility of this project.