Reputation: 3349
I have a main application which uses Dagger (some previous version) for providing dependencies.
Now, I am writing an SDK where I am using (Dagger 2.10+). Every thing works fine, when I have an application class, as applications has (HasActivityInjector) and it's responsible for the initialization of DaggerAppComponent.
My Question is -
Any suggestions would be great!!
Upvotes: 2
Views: 731
Reputation: 530
I recently had to tackle the same issue:
Create an SDK that can be used in any supported Android App.
I did have to accept the premise that some of the of the Apps that would want to use the SDK won't themselves be using Dagger or even dependency injection.
The major issue with creating an SDK that uses dependency injection is, as OP has pointed out, the Application implementation in the App.
Part of the reason behind the creation of the HasActivityInjector, HasFragmentInjector or HasSupportFragmentInjector has been the need to comply with the following dependency injection rule:
A class shouldn’t know anything about how it is injected. Reference A
With the creation of the HasXInjector interfaces, Android allows the the Dagger Dependency Graph to be attached to the Application, and then for the Application to be responsible for injecting the dependencies where they need to be injected through the following code:
AndroidInjection.inject(this) // <-- 'this' being an Activity or Fragment
SDK ISSUE
The issue is that the SDK does not have an Application implementation of its own. Additionally, the SDK can not add anything to the Application implementation of the App, nor can it override the Application implementation of the App.
In the case of an external SDK, it will not even know about an Application implementation, just the Application Interface.
So even if the Application that has included the SDK uses Dagger, which is not guaranteed, the SDK will not be able to add it's Dependency Graph to the Dependency Graph used by App's Application implementation, making all SDK dependencies unreachable.
And if the Application does not use Dagger, how would the dependencies be injected in the first place?
My own solution to this issue has been to break the rule quoted above and not use the HasActivityInjector, HasFragmentInjector or HasSupportFragmentInjector for injection internally in the SDK.
Upvotes: 3