Skip to content Skip to sidebar Skip to footer

How Do I Inject An Abstraction Using An Ioc Container Like Dagger 2

What I would like to do is to have an abstraction, and pass the abstraction as parameter. So that if one day something better than retrofit comes along and I want to switch it, it

Solution 1:

In Java, as in C#, abstractions are represented by interfaces or abstract classes.

What you are proposing might be called 'wrapping an external library in an interface to allow swapping by configuration'. To do that, you would have to inspect the methods exposed by the concretion that you want to be able to swap out and create a new interface that matches those.

For example, if the external library has methods like this:

publicclassExternalLibrary {
    voidfoo() {
        //foo implementation
    }

    voidbar() {
        //bar implementation
    }
}

You would create a wrapper interface:

publicinterfaceFooBarable {
    voidfoo();
    voidbar();
}

The next step is to make the consumers of ExternalLibrary in your app depend on FooBarable:

publicclassMyActivityextendsActivity {

    FooBar fooBar;

    publicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DaggerFooBarComponent
            .builder()
            .fooBarModule(newExternalLibraryModule())
            .build()
            .inject(this);
    }
}

If you need to swap ExternalLibrary for, say, a test mock, you can use a test component as per the instructions for testing in the Dagger 2 User Guide:

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DaggerTestFooBarComponent
            .builder()
            .mockFooBarModule(new MockFooBarableModule())
            .build()
            .inject(this);
    }

To see how the DI framework/IOC container Dagger 2 works with all of this, you would have to look at the user guide and the Google Dagger 2 Android app blueprint as there is too much to explain within the context of one answer.

Post a Comment for "How Do I Inject An Abstraction Using An Ioc Container Like Dagger 2"