A fast dependency injector for Android and Java.

Overview

Dagger

Maven Central

A fast dependency injector for Java and Android.

Dagger is a compile-time framework for dependency injection. It uses no reflection or runtime bytecode generation, does all its analysis at compile-time, and generates plain Java source code.

Dagger is actively maintained by the same team that works on Guava. Snapshot releases are auto-deployed to Sonatype's central Maven repository on every clean build with the version HEAD-SNAPSHOT. The current version builds upon previous work done at Square.

Documentation

You can find the dagger documentation here which has extended usage instructions and other useful information. More detailed information can be found in the API documentation.

You can also learn more from the original proposal, this talk by Greg Kick, and on the [email protected] mailing list.

Installation

Bazel

First, import the Dagger repository into your WORKSPACE file using http_archive.

Note: The http_archive must point to a tagged release of Dagger, not just any commit. The version of the Dagger artifacts will match the version of the tagged release.

# Top-level WORKSPACE file

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

DAGGER_TAG = "2.28.1"
DAGGER_SHA = "9e69ab2f9a47e0f74e71fe49098bea908c528aa02fa0c5995334447b310d0cdd"
http_archive(
    name = "dagger",
    strip_prefix = "dagger-dagger-%s" % DAGGER_TAG,
    sha256 = DAGGER_SHA,
    urls = ["https://github.com/google/dagger/archive/dagger-%s.zip" % DAGGER_TAG],
)

Next you will need to setup targets that export the proper dependencies and plugins. Follow the sections below to setup the dependencies you need.

Dagger Setup

First, load the Dagger artifacts and repositories, and add them to your list of maven_install artifacts.

# Top-level WORKSPACE file

load("@dagger//:workspace_defs.bzl", "DAGGER_ARTIFACTS", "DAGGER_REPOSITORIES")

maven_install(
    artifacts = DAGGER_ARTIFACTS + [...],
    repositories = DAGGER_REPOSITORIES + [...],
)

Next, load and call dagger_rules in your top-level BUILD file:

# Top-level BUILD file

load("@dagger//:workspace_defs.bzl", "dagger_rules")

dagger_rules()

This will add the following Dagger build targets: (Note that these targets already export all of the dependencies and processors they need).

deps = [
    ":dagger",                  # For Dagger
    ":dagger-spi",              # For Dagger SPI
    ":dagger-producers",        # For Dagger Producers
]

Dagger Android Setup

First, load the Dagger Android artifacts and repositories, and add them to your list of maven_install artifacts.

# Top-level WORKSPACE file

load(
    "@dagger//:workspace_defs.bzl",
    "DAGGER_ANDROID_ARTIFACTS",
    "DAGGER_ANDROID_REPOSITORIES"
)

maven_install(
    artifacts = DAGGER_ANDROID_ARTIFACTS + [...],
    repositories = DAGGER_ANDROID_REPOSITORIES + [...],
)

Next, load and call dagger_android_rules in your top-level BUILD file:

# Top-level BUILD file

load("@dagger//:workspace_defs.bzl", "dagger_android_rules")

dagger_android_rules()

This will add the following Dagger Android build targets: (Note that these targets already export all of the dependencies and processors they need).

deps = [
    ":dagger-android",          # For Dagger Android
    ":dagger-android-support",  # For Dagger Android (Support)
]

Hilt Android Setup

First, load the Hilt Android artifacts and repositories, and add them to your list of maven_install artifacts.

# Top-level WORKSPACE file

load(
    "@dagger//:workspace_defs.bzl",
    "HILT_ANDROID_ARTIFACTS",
    "HILT_ANDROID_REPOSITORIES"
)

maven_install(
    artifacts = HILT_ANDROID_ARTIFACTS + [...],
    repositories = HILT_ANDROID_REPOSITORIES + [...],
)

Next, load and call hilt_android_rules in your top-level BUILD file:

# Top-level BUILD file

load("@dagger//:workspace_defs.bzl", "hilt_android_rules")

hilt_android_rules()

This will add the following Hilt Android build targets: (Note that these targets already export all of the dependencies and processors they need).

deps = [
    ":hilt-android",            # For Hilt Android
    ":hilt-android-testing",    # For Hilt Android Testing
]

Other build systems

You will need to include the dagger-2.x.jar in your application's runtime. In order to activate code generation and generate implementations to manage your graph you will need to include dagger-compiler-2.x.jar in your build at compile time.

Maven

In a Maven project, include the dagger artifact in the dependencies section of your pom.xml and the dagger-compiler artifact as an annotationProcessorPaths value of the maven-compiler-plugin:

<dependencies>
  <dependency>
    <groupId>com.google.dagger</groupId>
    <artifactId>dagger</artifactId>
    <version>2.x</version>
  </dependency>
</dependencies>
<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.6.1</version>
      <configuration>
        <annotationProcessorPaths>
          <path>
            <groupId>com.google.dagger</groupId>
            <artifactId>dagger-compiler</artifactId>
            <version>2.x</version>
          </path>
        </annotationProcessorPaths>
      </configuration>
    </plugin>
  </plugins>
</build>

If you are using a version of the maven-compiler-plugin lower than 3.5, add the dagger-compiler artifact with the provided scope:

<dependencies>
  <dependency>
    <groupId>com.google.dagger</groupId>
    <artifactId>dagger</artifactId>
    <version>2.x</version>
  </dependency>
  <dependency>
    <groupId>com.google.dagger</groupId>
    <artifactId>dagger-compiler</artifactId>
    <version>2.x</version>
    <scope>provided</scope>
  </dependency>
</dependencies>

If you use the beta dagger-producers extension (which supplies parallelizable execution graphs), then add this to your maven configuration:

<dependencies>
  <dependency>
    <groupId>com.google.dagger</groupId>
    <artifactId>dagger-producers</artifactId>
    <version>2.x</version>
  </dependency>
</dependencies>

Gradle

// Add Dagger dependencies
dependencies {
  implementation 'com.google.dagger:dagger:2.x'
  annotationProcessor 'com.google.dagger:dagger-compiler:2.x'
}

If you're using classes in dagger.android you'll also want to include:

implementation 'com.google.dagger:dagger-android:2.x'
implementation 'com.google.dagger:dagger-android-support:2.x' // if you use the support libraries
annotationProcessor 'com.google.dagger:dagger-android-processor:2.x'

Notes:

If you're using the Android Databinding library, you may want to increase the number of errors that javac will print. When Dagger prints an error, databinding compilation will halt and sometimes print more than 100 errors, which is the default amount for javac. For more information, see Issue 306.

gradle.projectsEvaluated {
  tasks.withType(JavaCompile) {
    options.compilerArgs << "-Xmaxerrs" << "500" // or whatever number you want
  }
}

Resources

If you do not use maven, gradle, ivy, or other build systems that consume maven-style binary artifacts, they can be downloaded directly via the Maven Central Repository.

Developer snapshots are available from Sonatype's snapshot repository, and are built on a clean build of the GitHub project's master branch.

Building Dagger

See the CONTRIBUTING.md docs.

License

Copyright 2012 The Dagger Authors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Comments
  • Testing/Overriding Modules

    Testing/Overriding Modules

    Apologies if this is a dup (couldn't see an open issue).

    Is there any standard way to do testing. Overriding @Provides or extending module classes.
    I know it was discussed by Jake at Devvox that it still needs fleshing out.

    What are the current thoughts? This for me is the only real blocker. I can work around the limitations, but it feels like yak-shaving.

    area: documentation 
    opened by chrisjenx 70
  • Add optional support for generic injection

    Add optional support for generic injection

    One of the problems with using Dagger 2 (particularly on Android) is the need to call a different method for every class that needs injection. E.g. see this article which speaks of it as an annoyance: http://blog.gouline.net/2015/05/04/dagger-2-even-sharper-less-square/.

    People have handled this in different ways. Some just ignore it and have the class that needs injection bound at compile time to a particular component which to me means you are not actually doing DI because you cannot change your dependencies at run time.

    But I think I have a way that Dagger could add a small feature that would make this all so much easier. The feature would be optional and if you don't want to use it would have no impact on you.

    One of the ways that has been used to solve it is to use reflection and scan all the methods on the component to find inject methods and create a map from class to method. But it occurs to me that instead of resorting to reflection to create this map, it would be much handier if Dagger 2 would build this mapping for the user since it knows at compile time what the mapping is.

    So what I propose is this: In addition to the other Component methods you allow another method signature:

    public abstract <T> MembersInjector<T> someMethodName(Class<T> c);
    

    The presence of that method signature will be what controls this optional feature. When present the component generated will have the following added to it:

    • A field containing a Map<Class<>, MembersInjector<>>
    • The initialize method will generate code to fill the map which would basically just be a bunch of puts
    • The above method signature implementation would return a lookup from the map.

    That is the minimum level of support needed but it would be even nicer to allow a generic inject method as in:

    public abstract <T> void someMethodName(T instance);
    

    This method would also trigger creating the mapping. The implementation would look up in the map for the class of the instance to get an injector for doing injection. If it doesn't find one then it tries the superclass and so on up until it gets to java.lang.Object.

    What does it do if there is no injector for the given type? It should not throw an error. In the case of the return type being void it should do nothing. If the return type is T it should return null. You could also allow a boolean return value to indicate if injection succeeded. I suppose you could also declare an InjectionNotFound exception and if the method is declared to throw it then you throw the exception, but if it isn't declared, don't throw the exception.

    type: feature request area: dagger-android 
    opened by dalewking 62
  • Dagger 2.2 to 2.3 (or 2.4)

    Dagger 2.2 to 2.3 (or 2.4)

    I have updated my Dagger version from 2.2 to 2.3 and now facing following problem:

    Error:Execution failed for task ':app:compileDebugJavaWithJavac'. java.lang.NoSuchMethodError: com.google.common.collect.ImmutableSetMultimap$Builder.putAll(Ljava/lang/Iterable;)Lcom/google/common/collect/ImmutableSetMultimap$Builder;

    opened by AlokBansal8 48
  • Processor error on missing type while traversing too far up component dependency chain.

    Processor error on missing type while traversing too far up component dependency chain.

    Module 'test-a':

    public final class A {
      @Inject A() {}
    }
    
    @Component
    public interface ComponentA {
      A a();
    }
    

    Module 'test-b' which has implementation project(':test-a'):

    public final class B {
      @Inject B(A a) {}
    }
    
    @Component(dependencies = ComponentA.class)
    public interface ComponentB {
      B b();
    }
    

    Module 'test-c' which has implementation project(':test-b'):

    public final class C {
      @Inject C(B b) {}
    }
    
    @Component(dependencies = ComponentB.class)
    public interface ComponentC {
      C c();
    }
    

    fails with:

    > Task :test-c:compileDebugJavaWithJavac FAILED
    error: cannot access ComponentA
      class file for test.a.ComponentA not found
      Consult the following stack trace for details.
      com.sun.tools.javac.code.Symbol$CompletionFailure: class file for test.a.ComponentA not found
    1 error
    

    which makes sense, because 'test-c' isn't meant to see 'test-a' as it's an implementation detail of 'test-b', but why is Dagger in 'test-c' trying to do anything with ComponentA? Once it reaches ComponentB and sees the required B type exposed shouldn't it stop?

    type: feature request area: build P3 area: dagger 
    opened by JakeWharton 47
  • Leak while integrating with navigation component

    Leak while integrating with navigation component

    ┬───
    │ GC Root: System class
    │
    ├─ android.view.inputmethod.InputMethodManager class
    │    Leaking: NO (InputMethodManager↓ is not leaking and a class is never leaking)
    │    ↓ static InputMethodManager.sInstance
    ├─ android.view.inputmethod.InputMethodManager instance
    │    Leaking: NO (DecorView↓ is not leaking and InputMethodManager is a singleton)
    │    ↓ InputMethodManager.mNextServedView
    ├─ com.android.internal.policy.DecorView instance
    │    Leaking: NO (LinearLayout↓ is not leaking and View attached)
    │    mContext instance of com.android.internal.policy.DecorContext, wrapping activity com.mpierucci.android.hiltmemleak.MainActivity with mDestroyed = false
    │    Parent android.view.ViewRootImpl not a android.view.View
    │    View#mParent is set
    │    View#mAttachInfo is not null (view attached)
    │    View.mWindowAttachCount = 1
    │    ↓ DecorView.mContentRoot
    ├─ android.widget.LinearLayout instance
    │    Leaking: NO (MainActivity↓ is not leaking and View attached)
    │    mContext instance of com.mpierucci.android.hiltmemleak.MainActivity with mDestroyed = false
    │    View.parent com.android.internal.policy.DecorView attached as well
    │    View#mParent is set
    │    View#mAttachInfo is not null (view attached)
    │    View.mWindowAttachCount = 1
    │    ↓ LinearLayout.mContext
    ├─ com.mpierucci.android.hiltmemleak.MainActivity instance
    │    Leaking: NO (NavHostFragment↓ is not leaking and Activity#mDestroyed is false)
    │    ↓ MainActivity.mFragments
    ├─ androidx.fragment.app.FragmentController instance
    │    Leaking: NO (NavHostFragment↓ is not leaking)
    │    ↓ FragmentController.mHost
    ├─ androidx.fragment.app.FragmentActivity$HostCallbacks instance
    │    Leaking: NO (NavHostFragment↓ is not leaking)
    │    ↓ FragmentActivity$HostCallbacks.mFragmentManager
    ├─ androidx.fragment.app.FragmentManagerImpl instance
    │    Leaking: NO (NavHostFragment↓ is not leaking)
    │    ↓ FragmentManagerImpl.mPrimaryNav
    ├─ androidx.navigation.fragment.NavHostFragment instance
    │    Leaking: NO (Fragment#mFragmentManager is not null)
    │    ↓ NavHostFragment.mNavController
    │                      ~~~~~~~~~~~~~~
    ├─ androidx.navigation.NavHostController instance
    │    Leaking: UNKNOWN
    │    ↓ NavHostController.mOnDestinationChangedListeners
    │                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ├─ java.util.concurrent.CopyOnWriteArrayList instance
    │    Leaking: UNKNOWN
    │    ↓ CopyOnWriteArrayList.elements
    │                           ~~~~~~~~
    ├─ java.lang.Object[] array
    │    Leaking: UNKNOWN
    │    ↓ Object[].[0]
    │               ~~~
    ├─ androidx.navigation.ui.ToolbarOnDestinationChangedListener instance
    │    Leaking: UNKNOWN
    │    ↓ ToolbarOnDestinationChangedListener.mContext
    │                                          ~~~~~~~~
    ├─ dagger.hilt.android.internal.managers.ViewComponentManager$FragmentContextWrapper instance
    │    Leaking: UNKNOWN
    │    ViewComponentManager$FragmentContextWrapper wraps an Activity with Activity.mDestroyed false
    │    ↓ ViewComponentManager$FragmentContextWrapper.fragment
    │                                                  ~~~~~~~~
    ╰→ com.mpierucci.android.hiltmemleak.LeakFragment instance
    ​     Leaking: YES (ObjectWatcher was watching this because com.mpierucci.android.hiltmemleak.LeakFragment received Fragment#onDestroy() callback and Fragment#mFragmentManager is null)
    ​     key = 257b183a-777d-43c3-a1b0-0d470d6d415c
    ​     watchDurationMillis = 19270
    ​     retainedDurationMillis = 14268
    
    METADATA
    
    Build.VERSION.SDK_INT: 28
    Build.MANUFACTURER: Google
    LeakCanary version: 2.4
    App process name: com.mpierucci.android.hiltmemleak
    Analysis duration: 7339 ms
    

    The following leak is reported when integrating Hilt with fragments and navigation components. A full project to reproduce the leak can be found Here

    Basically you just need to add @AndroidEntryPoint to a fragment that updates the toolbar ( as suggested by the official documentation) and you'll get a leak when navigating back and forth.

    Since this issue does not happen if:

    • you do not add the entry point annotation

    or

    • you do not update the toolbar through navigation component

    I´ll report it in both libraries

    type: bug P2 area: hilt 
    opened by mpierucci 44
  • Inject into Workers (androidx.WorkManager API)

    Inject into Workers (androidx.WorkManager API)

    Hi, from latest Google I/O you just presented the new androidx.work.Worker class, part of the new WorkManager API.

    Since the Worker class is created by the framework (we only pass the Worker class type to the WorkManager), how can we @inject fields into the Worker ? Do you intend to add a new AndroidInjection.inject() function that takes a worker as argument ?

    Thanks

    opened by droidrcc 43
  • Dagger-2.17 An exception occurred: java.util.NoSuchElementException

    Dagger-2.17 An exception occurred: java.util.NoSuchElementException

    e: [kapt] An exception occurred: java.util.NoSuchElementException
    	at com.sun.tools.javac.util.List$2.next(List.java:432)
    	at com.google.common.collect.Iterators.getOnlyElement(Iterators.java:302)
    	at com.google.common.collect.Iterables.getOnlyElement(Iterables.java:254)
    	at dagger.android.processor.AndroidMapKeys.mapKeyValue(AndroidMapKeys.java:75)
    	at dagger.android.processor.AndroidMapKeys.lambda$annotationsAndFrameworkTypes$5(AndroidMapKeys.java:56)
    	at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1321)
    
    opened by tata168s 38
  • Class keys into map don't work in Kotlin 1.3.30

    Class keys into map don't work in Kotlin 1.3.30

    Setup:

    • AGP 3.3.x
    • Dagger 2.21+
    • Kotlin 1.3.30
    • Gradle 5.3.1

    Error:

    e: C:\gradle\build\DaggerKotlin\app\tmp\kapt3\stubs\debug\net\xpece\test\daggerkotlin\TheComponent.java:8: error: [Dagger/MissingBinding] java.util.Map<kotlin.reflect.KClass<? extends androidx.lifecycle.ViewModel>,javax.inject.Provider<androidx.lifecycle.ViewModel>> cannot be provided without an @Provides-annotated method.
    public abstract interface TheComponent {
                    ^
          java.util.Map<kotlin.reflect.KClass<? extends androidx.lifecycle.ViewModel>,javax.inject.Provider<androidx.lifecycle.ViewModel>> is injected at
              net.xpece.test.daggerkotlin.DaggerViewModelFactory(creators)
          net.xpece.test.daggerkotlin.DaggerViewModelFactory is injected at
              net.xpece.test.daggerkotlin.ViewModelModule.bindViewModelFactory(impl)
          androidx.lifecycle.ViewModelProvider.Factory is injected at
              net.xpece.test.daggerkotlin.MainActivity.vmf
          net.xpece.test.daggerkotlin.MainActivity is injected at
              net.xpece.test.daggerkotlin.TheComponent.inject(net.xpece.test.daggerkotlin.MainActivity)
    

    Current state:

    Injecting a Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>> based on KClass<out ViewModel keys produces an error.

    Changing to Map<KClass ... doesn't help.

    Expected state:

    Injecting a Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>> based on KClass<out ViewModel keys should work as before.

    Workaround:

    Migrate the class key annotation to Java.

    Relevant code:

    @Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
    @Retention(AnnotationRetention.RUNTIME)
    @MapKey
    annotation class ViewModelKey(val value: KClass<out ViewModel>)
    
    @Singleton
    class DaggerViewModelFactory @Inject constructor(
        private val creators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>
    ) : ViewModelProvider.Factory {
        // ...
    }
    
    @Module
    abstract class ViewModelModule {
    
        @Binds
        abstract fun bindViewModelFactory(impl: DaggerViewModelFactory): ViewModelProvider.Factory
    
        @Binds
        @IntoMap
        @ViewModelKey(ViewModelOne::class)
        abstract fun bindViewModelOne(impl: ViewModelOne): ViewModel
    
        @Binds
        @IntoMap
        @ViewModelKey(ViewModelTwo::class)
        abstract fun bindViewModelTwo(impl: ViewModelTwo): ViewModel
    }
    
    @Component(modules = [ViewModelModule::class])
    @Singleton
    interface TheComponent {
        fun inject(activity: MainActivity)
    }
    
    class MainActivity : Activity() {
    
        protected val component by lazy {
            DaggerTheComponent.create()
        }
    
        @Inject
        protected lateinit var vmf: ViewModelProvider.Factory
    
        protected val vm1: ViewModelOne by lazy { vmf.create(ViewModelOne::class.java) }
        protected val vm2: ViewModelTwo by lazy { vmf.create(ViewModelTwo::class.java) }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            component.inject(this)
            super.onCreate(savedInstanceState)
        }
    }
    

    Sample

    DaggerKotlin.zip

    opened by consp1racy 37
  • @Generated not found *javax.annotation.processing.Generated*

    @Generated not found *javax.annotation.processing.Generated*

    I am seeing this issue when trying to compile an Android project with Dagger2 (Google I/O 2018 sample app).

    package javax.annotation.processing does not exist
    import javax.annotation.processing.Generated;
    

    I have tried the several solutions mentioned in the issues and stack overflow for resolving javax.annoation.Generated but not having any luck. Note the annotation is in the javax.annotation.processing package.

    opened by ayvazj 35
  • Add support for incremental annotation processing in Gradle

    Add support for incremental annotation processing in Gradle

    My understanding is that currently, projects that include annotation processors are unable to be incrementally compiled in Gradle; such projects always trigger a full rebuild. The forthcoming Gradle version 4.7 will contain improvements that will allow for incremental annotation processing.

    https://docs.gradle.org/nightly/userguide/java_plugin.html#sec:incremental_annotation_processing

    Presuming Dagger fits into one of the two categories of annotation processor described in the above link, adding the required meta-data to the META-INF directory would likely significantly improve build times.

    opened by wrotte 33
  • error: cannot find symbol @Generated(  ^

    error: cannot find symbol @Generated( ^

    Building via Android Studio works fine, but if I call

    ./gradlew build

    I get

    error: cannot find symbol
    @Generated(
     ^
    
    

    all over the place. I'm using the latest version of dagger. My android project is set to Java 8 source. Calling java --version in my terminal tells me I have java 9 (which I'm not sure how, but I that's besides the point). Any ideas what I should be doing? I've seen a bunch of mixed answers on stackoverflow, but adding a dependency feels weird. My system being on java 9 doesn't make sense to me because I though Android Studio bundles it's own version of the JDK.

    opened by ColtonIdle 32
  • SavedStateHandle's creation is different from SavedStateViewModelFactory

    SavedStateHandle's creation is different from SavedStateViewModelFactory

    Hi Googler,

    In SavedStateViewModelFactory(from androidx.lifecycle:lifecycle-viewmodel-savedstate), it creates a SavedStateHandle for a ViewModel when there is a constructor with SavedStateHandle. https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:lifecycle/lifecycle-viewmodel-savedstate/src/main/java/androidx/lifecycle/SavedStateViewModelFactory.kt;l=127?q=SavedStateViewModelFactory

    private val ANDROID_VIEWMODEL_SIGNATURE = listOf<Class<*>>(
        Application::class.java,
        SavedStateHandle::class.java
    )
    private val VIEWMODEL_SIGNATURE = listOf<Class<*>>(SavedStateHandle::class.java)
    
    val constructor: Constructor<T>? = if (isAndroidViewModel && application != null) {
        findMatchingConstructor(modelClass, ANDROID_VIEWMODEL_SIGNATURE)
    } else {
        findMatchingConstructor(modelClass, VIEWMODEL_SIGNATURE)
    }
    // doesn't need SavedStateHandle
    if (constructor == null) {
        return factory.create(modelClass, extras)
    }
    

    But I found Hilt always creates a SavedStateHandle for each ViewModel in HiltViewModelFactory. https://github.com/google/dagger/blob/b5990a0641a7860b760aa9055b90a99d06186af6/java/dagger/hilt/android/lifecycle/HiltViewModelFactory.java#L75

    The reason is AbstractSavedStateViewModelFactory extended by HiltViewModelFactory doesn't handle the same case by default. And if the ViewModel is in the Fragment scope, the SavedStateHandle puts Fragment's arguments into itself first.

    What happened in my App:

    • A Fragment A with argument set B.
    • In Fragment A, it had 4 Fragment-scoped ViewModels without SavedStateHandle in their constructor.
    • So there were 4 SavedStateHandles with argument set B.
    • When my app pushed Fragment A 2x times, and then maked the Activity stop, like opening another Activity, Recent App or Launcher.
    • 2x Fragment A X 4 SavedStateHandles X argument set B

    TransactionTooLargeException happened when the Activity saved its state before stopping. Actually, all SavedStateHandles are unused in the case.

    Could you have a look on it?

    My current solution: Use the original way to implement ViewModels and inject dependencies from Hilt via EntryPoints. And Hilt will use SavedStateViewModelFactory to create these ViewModels.

    class ViewModel(
      application: Application
    ) : AndroidViewModel(application) {
    
      private val repository: Repository
    
      init {
        val entryPoint = application.viewModelEntryPoint()
        repository = entryPoint.repository()
      }
    }
    
    opened by AlanChiou 4
  • Inexplicable error in the execution of tests by Github actions

    Inexplicable error in the execution of tests by Github actions

    • What went wrong: java.lang.UnsupportedClassVersionError: dagger/hilt/android/plugin/HiltGradlePlugin has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0

    dagger/hilt/android/plugin/HiltGradlePlugin has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0

    Screenshot 2022-12-31 104432

    opened by VahidGarousi 1
  • Suggestion: Improve error message when Provider/Lazy are accidentally used in multibindings

    Suggestion: Improve error message when Provider/Lazy are accidentally used in multibindings

    This snippet may be accidentally written to declare a multibinding

    @Module
    interface Example {
      @Multibinding
      Map<String, Provider<String>> someBindings();
    }
    

    The error is that it's using a Provider in the declaration when it should just be Map<String, String>. However, the error message is a little confusing as it seems to imply that it's not a Map at all.

    error: @Multibinds methods must return Map<K, V> or Set<T>

    I think it would be easier for folks to debug if this message could be more explicit, such as mentioning that dagger intrinsic types like Provider and Lazy are not supported and mentioning if it sees one in the signature.

    type: bug P3 area: dagger 
    opened by ZacSweers 0
  • Using HiltAndroidApp annotation within the library module

    Using HiltAndroidApp annotation within the library module

    Hi, I'm trying to integrate Hilt in a multi-module android project(we don't use feature modules). Here is a current structure of our project

    • App Module
    • Lib Module 1 (This library has Application class MyApplication1 for app 1)
    • Lib Module 2 (This library has Application class MyApplication2 for app 2)
    • Lib module 3 (common stuff)
    • Up to Lib module 100

    If I put @HiltAndroidApp annotation on MyApplication1 I get this build error:

    Application class annotated with @HiltAndroidApp has to be defined in an android application project
      [Hilt] Processing did not complete. See error above for details.
    

    To address this issue, if I move the application classes MyApplication1 and MyApplication2 to the App module, I'll start getting circular dependency errors(because a library project cannot depend on App project). I've dozens of libraries and they have code(e.g. lateinit var app: MyApplication1, access app specific properties, etc.) which needs a reference to the Application object, hence I cannot have independent Application classes. If you are suggesting to refactor our code base to have independent Application module, then that would likely be a year long project(given how large our code base is)

    I also tried creating a separate app module(not library module) holding a base Application and made my MyApplication1 and MyApplication2 extend it, but I can't do that successfully, because Android Studio doesn't like a library-module depend on an application-module. And having a library-module depend on app-module doesn't sound like a good pattern, and going to cause other issues anyway.

    I came across this issue but the suggested solution on the issue won't work in my case(due to reasons mentioned above).

    Will Hilt ever support annotating an Application class with @HiltAndroidApp within the library modules?

    opened by grkep 5
  • AggregateDepsTask cache miss due to inconsistent order

    AggregateDepsTask cache miss due to inconsistent order

    We saw on several occasion a remote cache miss:

    • first build runs on CI (linux runner) and populates the cache
    • second build runs locally (mac os x) and requests the remote cache

    The miss is caused by classpath files of AggregateDepsTask being ordered differently in the 2 builds, see screenshot below: image

    A quick initial investigation lead me to this suspect: https://github.com/google/dagger/blob/master/java/dagger/hilt/android/plugin/main/src/main/kotlin/dagger/hilt/android/plugin/util/AggregatedPackagesTransform.kt#L49

    walkTopDown() does not return files in a consistent order between platforms (or even JDKs ?).

    type: bug area: hilt 
    opened by alextu 2
Releases(dagger-2.44.2)
  • dagger-2.44.2(Nov 14, 2022)

    What’s new in Dagger

    Bug fixes

    • Fixes #3633: Updated shading rules to include newly added classes in androidx.room.compiler to prevent class version conflicts with user dependency on Room.
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.44.1(Nov 11, 2022)

    What’s new in Dagger

    Bug fixes

    • Fixes #3619: Upgrades XProcessing jars to get upstream fix for enums in annotations (which were missing fully qualified name or import in generated code).
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.44(Sep 21, 2022)

    What’s new In Dagger

    Potentially breaking changes

    • Fixes #3531: Removed formatting from dagger.android generated source could be a breaking change for anyone relying on golden files for Dagger’s generated code. (d123efdf0)

    Bug Fixes

    • Fixes #3522: Avoids pre-validating the nearest enclosing type in the InjectProcessingStep. (1d74d1fd3)

    What’s new in Hilt

    Potentially breaking changes

    • Added ViewModelLifecycle. This can be injected in the ViewModelComponent and used to register listeners for when ViewModel#onCleared() is called. This change also includes a breaking change for anyone who implemented the ActivityRetainedLifecycle interface themselves. This should be rare though as this interface was not meant to be implemented by users. (55aa4c60a)

    Bug Fixes

    • Fixes #3478: Fixes an issue in Hilt's Gradle Plugin not configuring the aggregating task correctly on a com.android.test Gradle module. (ea39850c7)
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.43.2(Aug 3, 2022)

    What’s New In Dagger

    Bug Fixes

    • Fixes #3495: Updates the XProcessing jars, which should again be compatible with java 8. (62b7f4592)
    • Adds support reading metadata from Kotlin 1.8 by updating kotlin-metadata-jvm to 5.0. (353a50b1e)
    • Fixes an issue where the Hilt Gradle Plugin artifact was being bloated with additional classes causing its size to be way bigger than its suppose to be. (8235bebe9)
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.43.1(Jul 29, 2022)

    What’s New In Dagger

    Bug Fixes

    • Fixes #3480. Replace dependency on javax.annotation:jsr250-api:1.0 with javax.annotation:javax.annotation-api:1.3.2. (e9dc377d1)
    • Fixes #3483: Add onPluginEnd to BindingGraphPlugin, which will be called after all BindingGraphPlugins have been visited (34452751e)
    • Fixes #3476: Fix issue with Dagger generating mismatching parameter names in component inject functions. (90300d992)
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.43(Jul 21, 2022)

    What’s New In Dagger

    Potentially Breaking Changes

    Bug Fixes

    • Fixes #3401 where Dagger generated mismatched parameter names in subcomponent factory method implementations when the original factory method is in a separate build unit from the component that implements it.

    What’s New In Hilt

    Potentially Breaking Changes

    • Hilt now throws if the base activity/fragment class’s getDefaultViewModelProviderFactory() returns null. This is unlikely to happen though unless overridden by the user to return null. (9eee8e47f)
    • As part ViewModel bug fixes, dependencies were updated as below. androidx.navigation users will need to update to 2.5.0 to interoperate. These libraries require building with SDK 31. To build with SDK 31, AGP users will need to use AGP 7.0+. This will also require using JDK11.
      • androidx.activity and androidx.fragment to 1.5.0
      • androidx.lifecycle to 2.5.0
      • androidx.savedstate to 1.2.0

    Bug Fixes

    • Fix #3464 where SPI plugins were not being invoked with Hilt's Gradle Plugin aggregation (enableAggregatingTask) turned on. (b83887624)
    • Fixes #2328 and #3232 where getting multiple instances of @HiltViewModel with different keys would cause a crash.
    • Fixes #2152. hiltNavGraphViewModels is now no longer necessary to use @HiltViewModel with navigation backstack entries as the owner. The default ViewModelProvider.Factory from activities and fragments can be used directly with the backstack entry as the owner. (74ea7653a)
    • Make it so that map keys used with @BindValueIntoMap in Kotlin code do not need to use the @field notation. (e59183324)
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.42(May 9, 2022)

    What’s new in Dagger

    Potentially breaking changes

    As of this release, Dagger’s generated class will no longer extend the user-defined @Component annotated class (885b16dcf). This change was done to improve build times in certain scenarios by avoiding a known javac bottleneck. However, it may also be a breaking change for some users. For example

    // This will fail as of Dagger version 2.42
    DaggerMyComponent component = DaggerMyComponent.create();
    
    // Do this instead:
    MyComponent component = DaggerMyComponent.create();
    

    For migration purposes, we’ve added a temporary javac flag that can be used to re-enable the legacy behavior (the flag is disabled by default).

    -Adagger.generatedClassExtendsComponent=ENABLED
    

    This flag will be removed in a future version of Dagger.

    What’s new in Hilt

    Bug fixes

    • Fix two issues (e3d446873):
      1. matchingFallbacks being ignored work with Hilt.
      2. Hilt causing jetifier to execute twice.
    • Allow Hilt view constructor to contain non-declared types. (dc76e82c0)
    • Fix #3222. Generated fragment code previously would cause a Lint issue around LayoutInflater.from(). (850fc8474)
    • Fix #3329 where modules in a package with non-standard capitalization could cause an error in the Hilt Gradle Plugin. (029fe5702 and 329915f5f)
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.41(Feb 16, 2022)

    What’s New In Dagger

    Potentially Breaking Changes

    • This release fixes a recently noticed, but long-standing bug (#3136) where Dagger’s processors may silently miss a scope/qualifier on a binding if the scope/qualifier annotation is unresolvable (i.e. it is not on the classpath).

      Dagger will now prefer to fail the build if there are any unresolvable annotations present where a scope/qualifier is allowed. While Dagger does its best to avoid failing the build for non-scope/qualifier annotations, in general it’s not possible to tell if an annotation is a scope/qualifier unless its type is resolvable -- thus, Dagger may fail on non-scope/qualifier annotations as well.

      If these changes break your build, we recommend first trying to fix the breakage by adding the appropriate missing dependencies to your build (in most cases the error message should tell you exactly what type is missing). Although not recommended, you can revert back to the old behavior using the compiler option -Adagger.strictSuperficialValidation=DISABLED; however, this option will be removed in a future release. If the breakage is specifically due to the validation of transitive component dependencies, you may choose to disable that validation using -Adagger.validateTransitiveComponentDependencies=DISABLED. If the breakage is specifically due to androidx.hilt:hilt-lifecycle-viewmodel you will need to migrate to the native Hilt API (see https://github.com/google/dagger/issues/3257#issuecomment-1042627102).

    • This release fixes an accidental regression (introduced in Dagger version 2.39) that allowed requesting a raw @Inject constructor type which was previously not allowed (a61aa50c8).

      We expect breakages due to this issue to be relatively rare and easy to fix -- just replace the raw type with the proper parameterized type.

    • The string format of bindings has changed slightly (just spacing). SPI plugins that depend on this format may break. Note that as KSP migrations go forward, other string formats may change slightly in similar ways as well.

    New Changes

    • Dagger error messages for unresolvable deferred types have been improved. Error messages now tell you exactly which type could not be resolved and where it was found. Fixes #​​2208 (727068f38), Fixes #3133 (78646fbe6)

    • Dagger now supports reading the jakarta.inject versions of Inject, Scope, Qualifier, and Singleton. Dagger currently does not support jakarta.inject.Provider. Also, code generated by Dagger (and Hilt) continue to use the javax.inject symbols. Further changes and support to come in future releases. (219551376)

    Bug Fixes

    • Updates dagger-lint to avoid displaying a warning due to missing Vendor information. (cb33cc584)
    • Fixes an issue where Dagger's lint checks wouldn't work with lint 30.2.x-alpha due to using a removed API. (33ba899f9)
    • Fix #3069 where a class named "Create" could cause a conflict with the create() method on a component. (5ba04fb38)
    • Fix #3143 where a crash about a missing shard would occur when a members injection binding exists in a parent component. (3545f0193)
    • Fix #3091. Update MapKey error message to reference new auto-value artifacts. (91e7df18e)

    What’s New In Hilt

    New Changes

    • The Hilt Gradle Plugin now supports the updated Gradle plugins DSL as described in https://docs.gradle.org/current/userguide/plugins.html#sec:plugins_block via its new id: com.google.dagger.hilt.android. (e50aa067e)

    • There is now a new @CustomInject annotation to control when field injection occurs in an @HiltAndroidApp application class. See https://dagger.dev/hilt/custom-inject for details. (36c17bbff)

    Bug Fixes

    • Fix an issue where Hilt transform was not correctly updating the Signature attribute of an @AndroidEntryPoint whose superclass contained a type variable. (475cc0516)
    • Fixes #3119: Added kotlin-stdlib to pom dependencies to avoid breaking java-only projects. (3ec422e78)
    • Support AGP 7.2 ASM API changes (5502cd770)
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.40.5(Dec 6, 2021)

    Dagger bug fixes

    • Fixes #3090. Fixes an issue where the superficial validation for inject types was validating deeper than necessary and triggering failures when some classes were not available in the compile classpath.
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.40.4(Dec 2, 2021)

    What’s New in Dagger

    Bug Fixes

    Fix #3075: Fixes an issue where we were not deferring processing for a generated type in Kotlin source (745d30cf2)

    Source code(tar.gz)
    Source code(zip)
  • dagger-2.40.3(Nov 29, 2021)

    Dagger bug fixes

    • Fixes #3065: Fixes an issue caused by our XProcessing migration (to support KSP). For now, we’ve replaced all problematic usages of XElement#getName() with XElements#getSimpleName(XElement) which ensures we use the old javac simple name.
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.40.2(Nov 24, 2021)

    Dagger Bug Fixes

    • Fix #2997, #3032: Fixed issue with @BindsInstance parameters when bound types are from compiled dependencies. (ec1a98c).

    Hilt New features

    • Add convenient overloads for Kotlin users of EntryPointAccessors (6e1f0ea2c)
    • @AliasOf now accepts multiple scope annotations. (aa92b9e4c)

    Hilt Bug Fixes

    • Fix #3006:Sort dependencies in ComponentTreeDeps manually to give consistent output when doing incremental processing. (93f04ae1d)
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.40.1(Nov 11, 2021)

    Bug Fixes

    • Fix an AGP 7.2 incompatibility issue in the Hilt Gradle Plugin due to AGP breaking their API when cleaning up a deprecated type. (ed677ba1c)
    • Fix #2986 - An issue in the Dagger processor where it would crash due to a bad initialization. (608bcba38)
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.40(Oct 27, 2021)

    What’s New in Hilt

    New Changes

    • Flip the runtime flag default so that the fix is off and remove the compiler option for the Fragment.getContext() fix to make it easier to roll out the fix. This does not change the current default behavior of having the fix be off. (1c24b9718, e61ff7239)
    • Turn ON enableAggregatingTask by default in Hilt (90ea6a604)

    Bug fixes

    • EarlyEntryPoints#get() will now throw if there are no @EarlyEntryPoint annotated interfaces. (b5ef01c04)
    • Avoid using UAST implementation classes in Lint checkers. (44e1f056e)
    • Fix an issue where @OptionalInject activity/fragment classes could not be used with non-Hilt ViewModels. (8ef08fa07)
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.39.1(Oct 1, 2021)

    Hilt bug fixes

    • Fix #2834: Hilt processor now checks the correct "names" property when getting values from Kotlin @Suppress annotations. (db21d3fd1)
    • Fix #2904: Change toImmutableSet to use DaggerStreams rather than Guava. (43a7fe1ba)
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.39(Sep 30, 2021)

    What’s new in Hilt

    New breaking changes

    • The compiler flag shareTestComponents now defaults to true. This may significantly improve test compilation time for large projects, but is a breaking change for some tests due to changed visibility requirements. See Hilt’s flags documentation for details. (7e09cee32)
    • Hilt compiler flags are now strictly verified. Invalid flags will no longer compile. (742ba95e4)

    Bug fixes

    • Fix #2779: Dagger no longer requires the additional google repository mentioned in the Dagger 2.28 release notes. (01cf47b26)
    • There is now a runtime flag to control the Fragment.getContext() fix submitted in https://github.com/google/dagger/pull/2620. This allows enabling or disabling the fix without a compiler flag in order to permit a staged rollout. (c3f613f4c)
    • Fix #2789: Fixes issue with using EarlyEntryPoints being dropped when using enableAggregatingTask (38db196d7)
    • Fix a remote cache miss due to @Input parameter in ASM transform. (2f5003545)
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.38.1(Jul 27, 2021)

    Hilt bug fixes

    • Fix #2784. Fix an issue with AGP 7.0+ where the Gradle plugin bytecode transform was not applied to non-test code. This affected all @AndroidEntryPoint and @HiltAndroidApp classes that did not directly themselves extend from the Hilt-generated base class and meant that Hilt was not actually applied to those classes. (666df50b8)
    • Fix #2762. Fix an incompatibility with AGP 7.0.0-beta05 and 7.0.0-rc01 (09087db46)

    Dagger bug fixes

    • Fix #2765. Properly handle Kotlin metadata when shading dependencies. (ef7e7a1c0)
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.38(Jul 20, 2021)

    What’s New in Dagger

    New breaking changes

    Add the Google Maven repository for KSP artifacts

    As part of necessary changes in order to eventually support running Dagger as a KSP processor, Dagger now has a dependency on the KSP artifacts. These artifacts are available from the Google Maven repository, so this may break users who currently do not use this repository for other dependencies. The Google Maven repository is available at https://maven.google.com.

    Adding the repository in Gradle

    In your build.gradle file, add google() in repositories.

    repositories {
      google()
    }
    

    Example: https://github.com/google/dagger/blob/ff62b195c1a00727192154a409aa4ab0b796ff07/javatests/artifacts/dagger/simple/build.gradle#L23

    Adding the repository in Bazel

    If using the repository list from our workspace_defs.bzl, then no change is needed.

    Otherwise, pass "https://maven.google.com" to your usage of maven_install.

    maven_install(
        repositories = [
          "https://maven.google.com",
          ...
        ],
        ...
    )
    

    Adding the repository in Maven

    Add the repository in your pom.xml file like the following:

      <repositories>
        <repository>
          <id>google-maven</id>
          <name>Google Maven Repo</name>
          <url>https://maven.google.com</url>
        </repository>
      </repositories>
    

    Example: https://github.com/google/dagger/blob/ff62b195c1a00727192154a409aa4ab0b796ff07/examples/maven/pom.xml#L20

    Bug Fixes

    • Fix #2576. Check and give a better error message when a user added method has a name that is a java reserved keyword. (436ac2ec2)
    • Fix #2575. Check and give a better error message when a user added method has the same method signature as generated factory methods. (6971d0082)
    • Fix #2570. De-dupe assisted parameter names and field names to avoid a case where generated code may have naming conflicts. #2570 (3d93625ac)
    • Fix #2710. Allow Dagger-defined map keys (like ClassKey and StringKey) to be placed on fields in order to support Hilt's @BindValueIntoMap. (7af40dfff)
    • Errors for requesting bindings from the wrong component now include the component name for each binding along the dependency path for easier debugging. (2335e0f96)

    What’s New in Hilt

    This release fixes an incompatibility in the Hilt Gradle Plugin with AGP 7.0-beta04 and 7.1-alpha03. However, with this fix the HiltGradlePlugin will not work with alpha/beta versions of AGP 7.0 and 7.1 older than the versions previously mentioned. This fixes #2700. (be2f89ade)

    Bug Fixes

    • Fix #2710. Allow Dagger-defined map keys (like ClassKey and StringKey) to be placed on fields in order to support Hilt's @BindValueIntoMap. (7af40dfff)
    • Fix #2695. Fix an issue where enableAggregatingTask would not correctly generate Hilt classes when compiling in a dev environment with Windows OS. (a7c3c9ee5)
    • Fix #2672. Fix cast errors when getApplicationContext() is overridden. (4b695aefb)
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.37(Jun 10, 2021)

    What’s New in Dagger

    Bug Fixes

    • Fix #1079: Added an automatic module name to the com.google.dagger:dagger artifact to improve Java 9 compatibility. (cb308856a)
    • Removed the com.google.dagger:dagger-android-jarimpl artifact. This was an internal-only artifact, so its removal should not affect users. (6da2e7ea8)

    What’s New in Hilt

    Build performance improvements for Gradle

    There’s a new flag, enableAggregatingTask, supported by the Hilt Gradle plugin that allows Hilt to perform classpath aggregation in a dedicated Gradle task. This allows Hilt’s annotation processors to be “isolating” so that they are only invoked when necessary. This reduces incremental compilation times by reducing how often an incremental change causes a rebuild of the Dagger components. For details on how to enable this flag see https://dagger.dev/hilt/gradle-setup#aggregating-task.

    Note that the default for enableAggregatingTask is currently false, but it will be changed to true in an upcoming release, so please try to enable this flag and report any issues.

    Also, note that enableAggregatingTask will automatically enable sharing test components, so please read the caveats for enabling that flag as well.

    Finally, enableAggregatingTask replaces enableExperimentalClasspathAggregation which will be removed in an upcoming release. Please replace any usages of enableExperimentalClasspathAggregation with enableAggregatingTask.

    Bug Fixes

    • Fix #2662: Fixes an issue in Hilt's bytecode transform that would cause classes to fail validation if they contained an instantiation of an object whose type is the same as the superclass of the @AndroidEntryPoint annotated class. (839a84940)
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.36(May 26, 2021)

    What’s New in Dagger

    New breaking changes

    • Added compile time set binding validation for cases where the same binding key is bound into a set multiple times. Previously, cases of this could result in a runtime failure due to a similar check at runtime, but in rare cases that don’t trigger the runtime error, this could be a breaking change. (cf2047099)

    Bug Fixes

    • Make nested subcomponents and switching provider impls static within the generated component class. This is in preparation for eventually unnesting these classes from within their parent component to avoid issues that arise from deeply nested class names being too long. (d9f08aa3c)

    What’s New in Hilt

    Fragment#getContext() behavior fixed behind a flag

    Currently, a Hilt fragment’s getContext() method incorrectly continues to return a context value even after the fragment is removed. This differs from the behavior of a regular fragment. Fixing this is a breaking change that may introduce crashes at runtime if code incorrectly accessed the fragment’s context after removal and relied on Hilt’s incorrect behavior, so a flag has been introduced with the new fixed behavior default off.

    Please enable the flag with -Adagger.hilt.android.useFragmentGetContextFix=true to roll out this change at your own discretion. You may choose to, for example, start by enabling this only in development or some small testing population to find errors. In a future release, this flag will be defaulted to true and then in some release after that, the flag will be removed. (5ce0ceadd)

    Bug Fixes

    • Fix a bug where a Hilt fragment’s getContext() method could not be called before super.onAttach(). (8acc4336f)
    • Fix compatibility issue with the Hilt Gradle Plugin and Android Gradle Plugin 7.0 (371a2c366)
    • Fix lint issue with Hilt testing classes that get compiled to reference invalid ReflectiveOperationException for API < 19. (e58abc3f7)
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.35.1(Apr 28, 2021)

    Hilt bug fixes

    • Fix #2577: Adds a flag to disable the cross-compilation root validation that was enabled by default as of version 2.35. (See https://dagger.dev/hilt/compiler-options#disable-cross-compilation-root-validation for more details). (bfdb10962)
    • Reduce the possibility of OOMs in the local unit test transform task that is executed for users with AGP older than 4.2.0. (61ef9d879)
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.35(Apr 23, 2021)

    What’s New in Hilt

    Hilt is now stable!

    This means that Hilt is ready for use in production. Thanks for all the feedback through our alpha and beta stages! From now on, Hilt will no longer have alpha/beta releases and instead will be released with the same process as Dagger.

    New breaking changes

    • In the rare case that an app is relying on an @EarlyEntryPoint usage in a library that is built using an older version of Hilt, the @EarlyEntryPoint will no longer be picked up, resulting in a runtime error in tests (production code will be unaffected). To fix, all upstream usages of @EarlyEntryPoint must be built using this version of Hilt or later. (27a28276b)
    • Hilt now checks that builds with @HiltAndroidApp do not depend on targets with @HiltAndroidTest and vice versa as this can cause confusion with which modules are included in which Dagger components. Hilt version 2.35.1 adds a flag to disable this check.

    Bug fixes

    • Fix an issue where internal Kotlin object modules were incorrectly depended on directly by the component, which could result in a build failure if the component did not have visibility to the module. (115eaac88)
    • Fix an issue in the Hilt Gradle Plugin where determining AGP version failed if the AGP version being used was older than 3.6. (0218653f9)
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.34.1(Apr 13, 2021)

  • dagger-2.34(Apr 7, 2021)

    What’s New in Dagger

    Bug fixes

    • Fixed an issue where in rare cases subcomponent builder bindings might accidentally attach to the wrong parent (c2d097fa4)
    • Build performance improvements (47123ec9b, 1caa7f090, e2f2b2d96)

    What’s New in Hilt

    Hilt has a new flag, -Adagger.hilt.shareTestComponents, that enables tests with no test-specific bindings (e.g. @BindValue fields or @InstallIn modules within the test class) to share the same generated component. This flag should help improve build times by avoiding generating duplicate components for tests with the same bindings (faebc3c66).

    Note: This flag is currently disabled by default, but will be enabled by default in a future release of Hilt. For more information on how to enable this flag as well as some caveats, see the docs

    New breaking changes

    The alpha androidx extension @ViewModelInject is no longer supported. @ViewModelInject has been deprecated since androidx.hilt 1.0.0-alpha03 and was removed in androidx.hilt 1.0.0-beta01. Hilt now falls back to the base activity/fragment default ViewModelProviderFactory (3778ee2b8)

    Migration steps:

    Users of @ViewModelInject can migrate to @HiltViewModel which was added in Dagger 2.31.

    1. Add @HiltViewModel annotation to the class
    2. Replace the @ViewModelInject annotation on the constructor with @Inject.
    3. Remove @Assisted from the SavedStateHandle constructor parameter, if it exists
    4. Remove the old androidx.hilt:hilt-lifecycle-viewmodel dependency from your build.gradle file

    Bug fixes

    • Update the androidx fragment, lifecycle and activity dependencies which contain patch fixes. (efcdbe12, 57255db62)
    • Fix #2511: updates the kotlinx-metadata dependency. (b42731b50)
    • Fix issue with proguard removing entry points by adding proguard keep rules. (96171b0ef)
    • Fix #2456: Rename init() method in generated Activity to avoid conflict with user method of same name. (1c66033f5)
    • Reduce the possibility of KAPT logging warnings due to no processor supporting disableAndroidSuperclassValidation when no Android entry points are in the source module. (c70cf2d38)
    • Fix #2070: Clears the Fragment reference in FragmentContextWrapper after Fragment#onDestroy() to prevent leaks if a non-Hilt View outlives the Hilt Fragment that created it. (7f4c3a236)
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.33(Feb 25, 2021)

    What’s New in Dagger

    Bug fixes

    • Fixes #2370, #2396: Qualified @AssistedInject/@AssistedFactory types can now be provided and injected as normal bindings. (aff89b106)

    What’s New in Hilt

    Hilt is now in Beta!

    Previously, Hilt has been in Alpha, and it is now officially in Beta. This means that there will be no further changes to the APIs until after Hilt becomes stable. We’ll focus on bug fixes and getting Hilt into a stable release.

    (This also means that Hilt artifacts will now be postfixed with -beta instead of -alpha).

    New breaking changes

    Activity injection is now delayed until OnContextAvailableListener to enable member injecting ViewModels with SavedStateHandle. To use the ContextAware APIs androidx.activity, androidx.fragment and androidx.lifecycle dependencies are updated across the Dagger libraries. (623d3a61e)

    Note that this affects Hilt base classes that expected its members to be injected due to another Hilt class extending it. This essentially changes the injection of activities to occur within super.onCreate() instead of before super.onCreate().

    @AndroidEntryPoint
    public class MainActivity extends BaseActivity {
       // ...
    }
    
    abstract class BaseActivity extends FragmentActivity {
      @Inject Foo foo;
    
      @Override
       protected void onCreate(Bundle savedInstanceState) {
        foo.doSomething();  // <- This will now result in an NPE since ‘foo’ hasn’t been injected yet.
        super.onCreate();    
      }
    }
    

    For cases where a binding is strictly needed before super.onCreate() then the base class will have to invoke a Hilt generated method inject(). For example:

    abstract class BaseActivity extends FragmentActivity {
      @Override
       protected void onCreate(Bundle savedInstanceState) {
        inject(); // <- This will force early injection.
        foo.doSomething();
        super.onCreate();    
      }
    }
    
    // An inject method to be overridden by the Hilt generated class.
    protected void inject() {
      throw new UnsupportedOperationException();
    }
    

    Bug fixes

    • Allow entry points to be called in tests before the test instance is instantiated. This should help with issues like #2016 (For more details see https://dagger.dev/hilt/early-entry-point). (289f59fe8).
      • Warning: This API is marked @Beta (Unfortunately, the naming here is confusing because @Beta here means that this API is not considered stable -- the opposite from how the term is used in the Hilt “beta” release).
    • Fix an issue where Hilt's Gradle plugin was incompatible with Configuration Caching when enableExperimentalClasspathAggregation was turned ON. (b25eab897)
    • Fix issue with @DefineComponent classes with same name (785838e7d)
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.32(Feb 8, 2021)

    What’s New

    Dagger

    • Parameters in @AssistedFactory classes that have the same type now require a name to be set via @Assisted("foo") to disambiguate between arguments. Previously, order of parameters was used. Fixes #2281. (44d4f4b85)

    Bug fixes

    • Fix #2359: Fixes self-loop when a generated implementation of an @AssistedFactory method calls a generated component method with the same name. (e2c9a9a21)
    • Fix @AssistedFactory to allow for creating a parameterized Foo with type parameters specified by the factory. (552f430d2)
    • Issue #2279: Adds a better error message when trying to use a type parameter with an @AssistedFactory creator method. (9a9015190)
    • Fix #2309: Fix a type inference issue with generated assisted factories in Java 7. (cda6e32f1)

    Hilt

    • A new delayComponentReady() method on HiltAndroidRule allows deferring component initialization in tests until after test execution has started. This allows modifying @BindValue field values in the case that default component initialization would have otherwise requested them before an @Before or @Test method. (315b1fa30)
    • HiltAndroidRule now enforces that inject() is only called at most once per test case. (5dfd484bf)
    • Removes the deprecated ApplicationComponent. Note that this will now require upgrading any Androidx Hilt Worker dependencies to version 1.0.0-alpha03. (6592b06b2)
    • Fix #2337: Fix an incompatibility issue between the Hilt Gradle Plugin and AGP 4.2.0-beta04. Note that this fix makes it so that earlier versions of AGP 4.2.0 are incompatible with Hilt's Plugin. (9da5114b0)

    Bug fixes

    • Fix #2306: Fix an issue where internal Kotlin classes where not accessible with enableExperimentalClasspathAggregation turned ON. (53ceb9167, 98c73c619)
    • Fix an issue where an @InstallIn module referencing a component without a component builder would fail (132d9eab8)
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.31.2(Jan 21, 2021)

    Bug fixes

    • Issue #2300: Reverts an unintentional change to Hilt and dagger-android-support that depended on RC versions of AndroidX (850274b76)
    • Issue #2291: Reverts Hilt internal entry points back to public to avoid triggering an existing r8 optimization bug. (7a3d6fb3b)
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.31.1(Jan 20, 2021)

    Bug fixes

    • Adds back the deprecated ApplicationComponent since the latest androidx.hilt:hilt-work release still uses it. (b9325a45c)
    • Generated assisted factory classes are now final (6c11a603f)
    • @AssistedInject types can now be used as @Assisted parameters (c4d829d61)
    Source code(tar.gz)
    Source code(zip)
  • dagger-2.31(Jan 15, 2021)

    What’s New

    Dagger

    Assisted Injection

    Dagger now supports assisted injection. See the docs at https://dagger.dev/dev-guide/assisted-injection (daf0c6613)

    Hilt

    @TestInstallIn

    Adds a new @TestInstallIn feature to Hilt. This feature allows global test replacement modules to be defined instead of using @UninstallModules on individual tests. See the docs at (https://dagger.dev/hilt/testing#testinstallin) (d8284724a)

    @HiltViewModel

    Adds a new @HiltViewModel feature to Hilt. This replaces the @ViewModelInject AndroidX extension which will be deprecated in a future release. @HiltViewModel differs from @ViewModelInject in that ViewModels are now injected from a ViewModelComponent with accompanying @ViewModelScope. See the docs for using @HiltViewModel at (https://dagger.dev/hilt/view-model) and docs on the ViewModelComponent at https://dagger.dev/hilt/components (253ac8b34)

    Plugin local test support

    When used with AGP 4.2.0+, the Hilt Gradle plugin will now transform local test classes by default. Usages of enableTransformForLocalTests can be removed if using AGP 4.2.0+. See the docs at https://dagger.dev/hilt/gradle-setup#gradle-plugin-local-tests (d69b00f15)

    Experimental fix to classpath issues

    An experimental flag enableExperimentalClasspathAggregation has been introduced to the Hilt Gradle plugin to address issues where modules or entry points may be missed in multi-module Gradle projects when using implementation dependencies. It is recommended to use this flag since without it, if an implementation dependency hides a Hilt module/entry point, the resulting errors can be subtle and/or confusing and in the case of multibindings, may only manifest at runtime. However, there are also some build time tradeoffs to consider. See the docs at https://dagger.dev/hilt/gradle-setup#classpath-aggregation (239768bcc)

    ApplicationComponent removed

    The deprecated ApplicationComponent symbol has been removed. Users should migrate to SingletonComponent. This is intended to be a pure rename/functional no-op. (37cb8c842)

    Source code(tar.gz)
    Source code(zip)
  • dagger-2.30.1(Nov 24, 2020)

    Bug fixes

    • Sets the default value for experimentalDaggerErrorMessages back to disabled since it breaks hyperlinks in AndroidStudio (6a8bbbf03) . Note that this reverses the change to the default value made in the release 2.30.
    • Fixes #2190: Dagger was unnecessarily inspecting all fields of a class and attempting to find their Kotlin metadata, which sometimes led to crashing the processor. Now, Dagger inspects the Kotlin metadata lazily, and only on the fields that require it. (a885c85cb)
    Source code(tar.gz)
    Source code(zip)
Owner
Google
Google ❤️ Open Source
Google
Lightweight dependency injection for Java and Android (JSR-330)

About Feather Feather is an ultra-lightweight dependency injection (JSR-330) library for Java and Android. Dependency injection frameworks are often p

Zsolt Herpai 341 Nov 29, 2022
Guice (pronounced 'juice') is a lightweight dependency injection framework for Java 6 and above, brought to you by Google.

Guice Latest release: 5.0.1 Documentation: User Guide, 5.0.1 javadocs, Latest javadocs Continuous Integration: Mailing Lists: User Mailing List Licens

Google 11.7k Dec 29, 2022
JayWire Dependency Injection

JayWire Dependency Injection A very small and lightweight dependency injection framework for Java 8 without magic. Main features are: 100% pure Java c

VanillaSource 52 Jul 13, 2022
Dynamic Context Dependency Injection

Welcome to the Project Dynamic CDI JDK Informations Actual version is running from JDK8 up to JDK13. The version 1.0.x is based on JDK8. The implement

Sven Ruppert 8 Dec 10, 2019
Netflix, Inc. 809 Dec 28, 2022
Xposed Injector by Saygus, and project fixed by Spring Musk

Xposed Injector Xposed Injector to mod games externally. Made by Saygus, and project fixed by Spring Musk. Spring Musk requested me to upload his proj

Menu Modder 10 Nov 1, 2022
Backdoor injector for Bukkit/Spigot plugins.

MinePatcher Backdoor injector for Bukkit/Spigot plugins. MinePatcher was developed to test the security systems of Minecraft servers. Usage: 1. Window

null 3 Sep 18, 2022
Lightweight dependency injection for Java and Android (JSR-330)

About Feather Feather is an ultra-lightweight dependency injection (JSR-330) library for Java and Android. Dependency injection frameworks are often p

Zsolt Herpai 341 Nov 29, 2022
Android Auto Apps Downloader (AAAD) is an app for Android Phones that downloads popular Android Auto 3rd party apps and installs them in the correct way to have them in Android Auto.

Android Auto Apps Downloader (AAAD) is an app for Android Phones that downloads popular Android Auto 3rd party apps and installs them in the correct way to have them in Android Auto.

Gabriele Rizzo 865 Jan 2, 2023
Fast and Easy mapping from database and csv to POJO. A java micro ORM, lightweight alternative to iBatis and Hibernate. Fast Csv Parser and Csv Mapper

Simple Flat Mapper Release Notes Getting Started Docs Building it The build is using Maven. git clone https://github.com/arnaudroger/SimpleFlatMapper.

Arnaud Roger 418 Dec 17, 2022
Sauron, the all seeing eye! It is a service to generate automated reports and track migrations, changes and dependency versions for backend services also report on known CVE and security issues.

SAURON - VERSION AND DEPLOYMENT TRACKER DESCRIPTION Sauron, the all seeing eye! It is a service to generate automated reports and track migrations, ch

FREENOWTech 20 Oct 31, 2022
Guice (pronounced 'juice') is a lightweight dependency injection framework for Java 6 and above, brought to you by Google.

Guice Latest release: 5.0.1 Documentation: User Guide, 5.0.1 javadocs, Latest javadocs Continuous Integration: Mailing Lists: User Mailing List Licens

Google 11.7k Dec 29, 2022
A light-weight and dynamic dependency injection framework

⚠️ This project is now part of the EE4J initiative. This repository has been archived as all activities are now happening in the corresponding Eclipse

Java EE 105 Dec 23, 2022
Yet another Java annotation-based command parsing library, with Dependency Injection inspired by Guice

Commander A universal java command parsing library Building This project uses Gradle. Clone this repository: git clone https://github.com/OctoPvP/Comm

OctoDev 4 Oct 2, 2022
JayWire Dependency Injection

JayWire Dependency Injection A very small and lightweight dependency injection framework for Java 8 without magic. Main features are: 100% pure Java c

VanillaSource 52 Jul 13, 2022
This open source project allows you to easily integrate Camunda's External Task Clients into Micronaut projects: simply add a dependency in your Micronaut project

micronaut-camunda-external-client This open source project allows you to easily integrate Camunda 's External Task Clients into Micronaut projects. Mi

Novatec Consulting GmbH 19 Dec 18, 2022
Spring Kurulumundan Başlayarak, Spring IOC ve Dependency Injection, Hibernate, Maven ve Spring Boot Konularına Giriş Yapıyoruz.

Spring Tutorial for Beginners File Directory Apache Tomcat Apache Tomcat - Eclipse Bağlantısı Spring Paketlerinin İndirilmesi ve Projeye Entegrasyonu

İbrahim Can Erdoğan 11 Apr 11, 2022
Zero-dependency Reactive Streams publishers library

⚡️ Mutiny Zero: a zero-dependency Reactive Streams publishers library for Java Mutiny Zero is a minimal API for creating reactive-streams compliant pu

SmallRye 14 Dec 14, 2022
Dynamic Context Dependency Injection

Welcome to the Project Dynamic CDI JDK Informations Actual version is running from JDK8 up to JDK13. The version 1.0.x is based on JDK8. The implement

Sven Ruppert 8 Dec 10, 2019