Integrate Dagger 2 with Room Persistence Library in few lines

Marco Cattaneo
2 min readSep 22, 2017

--

During the Google IO 2017 was showed the Android Architecture Components, in this libraries set we can find Room, Room is an ORM created by Google that allow Developers to create a SQL Lite database without boilerplate code but with fiew annotations, the rest of code is auto-generated by Android Studio.

I will not explained how use Room, the web is full of these articles, i will only show how use it with Dagger 2, and how inject DAO and Room dabatase instance.

I’ll assume that you already know how Dependency Injection works, and how create Entity and Dao in Rooms. This is the application we will modify to integrate Dagger 2:

Demo app Structure

We have an entity named Product with his DAO (ProductDao), a DemoDatabase that extends RoomDatabase superclass and finally a repository pattern with: ProductRepository interface and ProductDatasource implementation.

Our Goal is to provide via Dagger 2 the Product Repository implementation, to use that to access Product table’s data.

Prepare elements to inject

First of all we should modify the DemoDatabase to expose a method that allow to get the DAO implementation in this way:

is important to make the class and method as abstract, Room will return the right DAO implementation. The Product DAO is used by ProductDatasource to grant the access to Product table’s data as below (look the injected constructor, it will recive the ProductDAO).

Module and Components

Now we need to create two modules: AppModule and RoomModule, the first is only for the Application Context , the second will provides RoomDatabase and Room DAO instances.

Simple, it’s a standard AppModule who provides the Application context. The RoomModule is more interesting:

This class will provide all we need to create a ProductDatasource, the DemoDatabase instance (from context), the ProductDao (from DemoDatabase) and finally the ProductRepository (form ProductDao). Now the component:

It uses our two modules, below the implementation of that inside a sample MainActivity:

I hope to have helped you, you can also find the full code in this Github project.

--

--

Marco Cattaneo
Marco Cattaneo

Responses (10)