Skip to content

Dependency Injection

zippy1978 edited this page Oct 17, 2014 · 1 revision

fastnail provides a lightweight dependency injection engine working at compile time (no overhead due to reflection).

To configure dependency injection:

1. Create a config.json file in res/raw folder of your application.

This file is responsible for configuring the application context.

components section is used to declare every component that can be injected.

Each componenent is then declared by it's name and must provide at least it's class name.

The optionnal singleton boolean property (default is false) can be set to ensure a single instance of the component is used by the whole application.

Here is an example:

{
    "components": {
        "myManager": {
            "className": "fr.grousset.fastsnail.test.MyManager",
            "singleton": true
        }
    }
}

2. Load the object graph

The object graph must be loaded at application startup. This can be done like this in the application class:

public class MyApplication extends Application {

    @Override
    public void onCreate() {

        // Load graph
        ObjectGraph.load(R.raw.config, this)

    }
}

3. Inject components anywhere you need them

Use the @InjectComponent annotation:

class HomeActivity extends Activity {

    @InjectComponent MyManager myManager

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState)

        myManager.sayHello()
    }
}

Name of the component can be provided as well if it does not match the field name (incuding the Android member naming convention starting with m):

@InjectComponent(name='myManager') AsyncManager mMyManager