logo
down
shadow

Provide instance without interface using Dagger


Provide instance without interface using Dagger

Content Index :

Provide instance without interface using Dagger
Tag : kotlin , By : James B
Date : November 28 2020, 04:01 AM

it fixes the issue When you use constructor injection Dagger can construct the object for you and you're already using Dagger to create ModelImpl to use it as a binding for Model in your example!
class ModelImpl @Inject constructor(...): Model{}

@Provides
fun model(inst: ModelImpl): Model = inst

// somewhere else...
// both variants would work!
@Inject lateinit var modelImpl : ModelImpl
@Inject lateinit var model : Model
class ModelImpl @Inject constructor(...)

// somewhere else...
@Inject lateinit var model : ModelImpl
// foo and bar can both be constructor injected
class Foo @Inject constructor()
class BarImpl @Inject constructor(val foo : Foo) : Bar

@Module
interface BarModule() {
  @Binds  // you should prefer Binds over Provides if you don't need initialization
  // barImpl can be constructor injected, so it can be requested/bound to its interface here
  fun bindBar(bar : BarImpl) : Bar
}

@Component(modules = BarModule::class)
interface BarComponent {
  fun getBar() : Bar // returns barImpl due to binding
}

@Inject lateinit var bar : BarImpl // but we could as well use the implementation directly
@Inject lateinit var bar : Foo // or just foo

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Dagger 2 - two provides method that provide same interface


Tag : java , By : Raghu
Date : March 29 2020, 07:55 AM
this will help I recently post the answer to a question like this in this post :
Dagger 2 : error while getting a multiple instances of same object with @Named
@Module
public class ApplicationModule {
private Shape rec;
private Shape circle;

public ApplicationModule() {
    rec = new Rectangle();
    circle= new Circle ();
}

@Provides
 @Named("rect")
public Shape provideRectangle() {
    return rec ;
}

@Provides
 @Named("circle")
public Shape provideCircle() {
    return circle;
}
@Inject
@Named("rect")
 Shape objRect;
@field:[Inject Named("rect")]
lateinit var objRect: Shape

Dagger 2: Provide same instance between multiple Component with same Scope on different library modules


Tag : java , By : Zinovate
Date : March 29 2020, 07:55 AM
Any of those help Remove the injection sites from your CoreComponent - it now has the sole function of exposing the binding for CoreRepository to its dependent components:
@Singleton
@Component(modules = {CoreModule.class})
public interface CoreComponent {
    CoreRepository coreRepository();
}
public class MyApplication extends Application {
    private final CoreComponent coreComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        coreComponent = DaggerCoreComponent
                            .coreModule(new CoreModule())
                            .build();
    }

    public static CoreComponent getCoreComponent(Context context) {
        return ((MyApplication) context.getApplicationContext()).coreComponent;
    }
}
@Scope
@Retention(RetentionPolicy.RUNTIME) public @interface PerActivity {}
@PerActivity
@Component(dependencies = {CoreComponent.class})
public interface ActivityComponent {
    void inject(FooActivity activity);

    void inject(BarActivity activity);
}
public class FooActivity extends AppCompatActivity {
        @Inject
        public CoreRepository repo;

        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            CoreComponent coreComponent = MyApplication.getCoreComponent(this);
            DaggerActivityComponent.builder()
                .coreComponent(coreComponent)
                .build()
                .inject(this);
        }
    }
}

Can dagger provide different implementations of the interface, depending on requested type?


Tag : development , By : mediafarm
Date : March 29 2020, 07:55 AM
it should still fix some issue This really depends on what you are trying to accomplish. You have 2 basic setups, whether you want to access your different implementations at once, or just want to supply one.
Access them at the same time / within the same scope
@Binds
@Qualifier("twitter")
Api provideApi(TwitterApi api);
@Inject @Qualifier("twitter") Api api;
@Component
interface ApiComponent {
  Api api();

  @Component.Builder
  interface Builder {
    @BindsInstance Builder api(Api api);
    ApiComponent build();
  }
}

(Dagger 2) Provide same instance for different types in MVP


Tag : android , By : 22.
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , You can use constructor injection along with the @Binds annotation in your module to achieve this. Simply add a constructor and annotate it with @Inject in MyView. You can then mark MyView as @Singleton so that the same instance is used everywhere(assuming the component is also scoped with @Singleton).
@Singleton
class MyView extends MyAbstractView implements MyViewContract {
    @Inject
    public MyView() {}
}

@Module
abstract class MyModule {
    @Binds
    abstract MyInterface provideMyInterface(MyView myView);

    @Binds
    abstract MyViewContract provideMyViewContract(MyView myView);
}

Dagger can't inject a parameter of type interface on a ViewModel's constructor using Dagger Android


Tag : android , By : geo
Date : March 29 2020, 07:55 AM
wish of those help Solved the issue. Using a generic view model factory found in this Github issue:
https://github.com/google/dagger/issues/1273#issuecomment-447997439
Related Posts Related QUESTIONS :
  • Kotlin ktor exposed DSL insert with reference
  • What does the AT symbol mean in KOTLIN
  • Efficiently make a view of (or copy) a subset of a large HashMap in Kotlin
  • SonarQube + Jacoco - Unable to read Koin module test coverage
  • Kotlin async/await syntax without blocking caller
  • Kotlin Class should have a single no-arg constructor
  • Kotlin Wildcard Capture on List Callback Parameter
  • How to pass functions to function in Kotlin
  • How can I serialize kotlin exposed sql dao
  • Difference between Any type and Generics in Kotlin
  • Kotlin : Interface with immutable property implemented by class with mutable
  • Idiomatic way to create n-ary cartesian product (combinations of several sets of parameters)
  • Serve favicon.ico and other static files with VertX
  • How to implement a getComponent(/*Class*/) method for video game in kotlin
  • For comprehensions with kotlin and arrow-kt library
  • how to access companion object from object instance in kotlin?
  • Protected members not accessible in extension functions?
  • ktor client https request with self-signed certificate
  • Kotlin contracts: link not-null of two properties
  • Kotlin coroutines: concurrent execution throttling
  • Kotlin: Update Immutable List Element
  • Kotlin with-statement as an expression
  • Kotlin class delegation features
  • Why does let not give me a non nullable integer in this case
  • Kotlin sequence concatenation
  • Kotlin - Create custom ext function for SpannableStringBuilder without duplicate arguments when declaring start, end &am
  • Kotlin actors goes to dead lock when capacity is less than number of messages
  • Can you concatenate statements at run-time in Kotlin?
  • Kotlin synchronized doesn't work properly
  • ojAlgo - Expressing Variables as Boundaries in Optimization?
  • Documenting Ktor routes with KDoc
  • Convert Set<Int> to varargs efficiently in Kotlin
  • Getting an error Using 'body(): ResponseBody?' is an error. moved to val with okhttp
  • Kotlin String to Int or zero (default value)
  • Return value only of the faster coroutine
  • Is there a Kotlin Coroutines Channel equivalent of RxJava's onDispose?
  • Create fat jar from kotlin multiplatform project
  • Short circuiting operation in Kotlin sequences
  • How to output deprecation warnings for Kotlin code?
  • Why does generated getter method have dollar signs in it?
  • For a final class why does when complain?
  • Reference value of constant with KDoc
  • How to create this coroutines in kotlin?
  • OkHttp: NoSuchMethodError copyInto in TlsUtil
  • Why do unreachable statements method not result in a compilation error?
  • Static/Const map key check at compile time
  • Escaping double quotes inside backticks
  • Does Kotlin have primitive types?
  • What is exactly null in kotlin and why i can't cause NPE with it?
  • Why would you use a Kotlin companion object rather than an initializer block for creation?
  • how to use operator overloading in Kotlin to divide a number by a numeric vector
  • How to use get() with backing fields in kotlin
  • How to map string to function and call it later
  • Kotlin enum constructor argument 'must be initialized' with companion object constant without qualifier name
  • Please explain to me class delegation in Kotlin
  • Error:(1, 41) Kotlin: Symbol is declared in module 'jdk.internal.opt' which does not export package 'jdk.i
  • How to properly make blocking service calls with Kotlin coroutines?
  • Gson SerializedName in a Kotlin interface
  • Kotlin convert FileTime to day, month, year
  • Kotlin how to move a file to a other directory?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com