Java Azure Function Dependency Injection

30 views Asked by At

I created an eventhub trigger azure function with Micronaut and running it locally but @Inject would inject dependency sometimes not other times, I was seeing NullPointerException. I was confused why DI is not working all the times, I thought if it is a Micronaut issue so I created a vanilla(withouot Micronaut) eventhub trigger function. This time I used Google Guice and followed this example but when I ran the function it did not inject any dependency and was throwing NPE all the time.

Function entry class

public class Function {

    @Inject
    EventHubMessageProcessor eventHubMessageProcessor;

    @FunctionName("DummyFa")
    public void run(
            @EventHubTrigger(name = "message",
                    eventHubName = "hub",
                    connection = "connection-string",
                    consumerGroup = "monitoring",
                    cardinality = Cardinality.ONE)
        String message,
        final ExecutionContext context) {

        try {
            context.getLogger().warning("Invocation - " + context.getInvocationId());
            context.getLogger().warning("Is EventHubMessageProcessor Null :" + (eventHubMessageProcessor == null));
            eventHubMessageProcessor.process(message, context);
        } catch (Exception e) {
            context.getLogger().severe(e.getMessage());
        }
    }
}

DI Hook

public class FunctionGuiceFactory implements FunctionInstanceInjector {
    @Override
    public <T> T getInstance(Class<T> functionClass) {
        return Guice.createInjector(new DiModule()).getInstance(functionClass);
    }
}

In above example eventHubMessageProcessor is always null with Guice but get instantiated with Micronaut for most of the times(not always as it should).

0

There are 0 answers