Dependency Injection in AWS Lambda function

In this Article, we will see how to use Guice Dependency injection when working with existing application or service.

Let’s assume we have a service class.

public interface BookService {
    List<Book> getBookMetadata();
}

and its implementation

public class BookServiceImpl implements BookService{

    @Override
    public List<Book> getBookMetadata() {
        // return list of Book object
}

Binding Class used for the above service

public class ApplicationModule extends AbstractModule
{
  protected void configure() {

    bind(BookService.class).to(BookServiceImpl.class);
  }
}

We need to create a Lambda which gets the book metadata from the BookService when triggered by S3Event.

public class TestLambda implements RequestHandler<S3Event, Object> {   

    private BookService bookService;

        @injest
    public TestLambda(BookService bookservice) { // error
                this.bookService = bookservice;
    }

    public Object handleRequest(S3Event request, Context context) {

        List<Book> booklist = bookService.getBookMetadata();
                ...
   }
}

The above code gives the following error no public zero-argument constructor as the lambda expects constructor without any argument.

Instead you can use add the following to your Lambda class to use Guice dependency injection

Injector injector = Guice.createInjector(new ApplicationModule());
bookService = injector.getInstance(BookService.class);

Final Lambda code looks like the following

public class TestLambda implements RequestHandler<S3Event, Object> {   

    private BookService bookService;

    public TestLambda(BookService bookservice) {
                Injector injector = Guice.createInjector(new ApplicationModule());
                this.bookService = injector.getInstance(BookService.class);
    }

    public Object handleRequest(S3Event request, Context context) {

        List<Book> booklist = bookService.getBookMetadata();
                ...
   }
}