使用Dagger2进行内部依赖注入 [英] Internal dependency injection using Dagger2

查看:82
本文介绍了使用Dagger2进行内部依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Dagger2。

I want to use Dagger2.

说我有以下依赖项:


  • A类依赖于B类

  • B类依赖于C类

I试图创建一个提供B和C的模块,以及一个提供A的组件,但是只有B被注入到A中,并且B中对C的引用仍然为空。

I tried to create a Module that provides B and C, and a Component that provides A, however only B is injected into A, and the reference to C in B remains null.

我需要使用匕首实现什么类结构?

What is the classes structure I need to implement using dagger?

推荐答案

您可以使用构造函数注入或字段注入;

You can either use constructor injection or field injection; and either constructor-inject or module-inject.

Constructor- @ Inject可能有问题,因为自从黎明以来我就一直在使用Modules and Components。

Constructor-@Inject might be buggy, because I've been using Modules and Components since the dawn of time.

@Singleton
public class A {
    B b;

    @Inject
    public A(B b) {
        this.b = b;
    }
}

@Singleton
public class B {
    C c;

    @Inject
    public B(C c) {
        this.c = c;
    }
}

@Singleton
public class C {
    @Inject
    public C() {
    }
}

@Singleton
@Component
public interface SingletonComponent {
    void inject(MainActivity mainActivity);
}

public class A {
    private B b;

    public A(B b) {
        this.b = b;
    }
}

public class B {
    private C c;

    public B(C c) {
        this.c = c;
    }
}

public class C {
}

@Module
public class ProviderModule {
    @Provides
    @Singleton
    public A a(B b) {
        return new A(b);
    }

    @Provides
    @Singleton
    public B b(C c) {
        return new B(c);
    }

    @Provides
    @Singleton
    public C c() {
        return new C();
    }
}

@Component(modules={ProviderModule.class})
@Singleton
public interface SingletonComponent {
    A a();
    B b();
    C c();

    void inject(MainActivity mainActivity);
}

或带电场注入

@Singleton
public class A {
    @Inject
    B b;

    @Inject    
    public A() {
    }
}

@Singleton
public class B {
    @Inject
    C c;

    public B() {
    }
}

@Singleton
public class C {
    @Inject
    public C() {
    }
}

@Component
@Singleton
public interface SingletonComponent {
    A a();
    B b();
    C c();

    void inject(MainActivity mainActivity);
}

这篇关于使用Dagger2进行内部依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆