如何使用Dagger 2 @Provide服务

时间:2019-08-12 08:27:20

标签: android dagger-2 mvp

我在MVP应用程序中将Dagger 2用于DI。该应用程序具有不同的服务,这些服务负责发出请求,例如获取产品数据或下订单。

大多数时候,每个屏幕都有自己的@Component界面和@Module类,并在这些模块中提供相应的演示者。

在某些情况下,服务仅由一个演示者使用。在这种情况下,我只是在该模块中@Provide。但是我有很多服务在不同的演示者中多次使用。目前,我将它们全部放在ApplicationModule中,将它们暴露在ApplicationComponent中,如果他们的演示者需要一项服务,则在“屏幕组件”中为ApplicationComponent添加依赖项。现在的问题是,几乎每个组件都依赖于ApplicationComponent,我认为这是错误的。

我该如何处理最佳方法?我应该为每个服务创建一个模块并将其添加到需要它的组件中吗?我也想记住作用域,并认为应该将服务添加到@Singleton范围。

ApplicationComponent

@Singleton
@Component(modules = {ApplicationModule.class, ContextModule.class}
public interface ApplicationComponent {

    void inject(MyApplication application);

    Context getContext();
    ProductDataService getProductDataService();
    AnalyticsService getAnalyticsService();
    CartService getCartService();
    ...
}

ApplicationModule

@Module
public class ApplicationModule {

    @Provides
    static ProductDataService provideProductDataService(ProductDataServiceImpl productDataService) {
        return productDataService;
    }

    @Provides
    static AnalyticsService provideAnalyticsService(AnalyticsServiceImpl analyticsService) {
        return analyticsService;
    }

    @Provides
    static CartService provideCartService(CartServiceImpl cartService) {
        return cartService;
    }

    ...
}

ProductDataServiceImpl

@Singleton
public class ProductDataServiceImpl implements ProductDataService {

    private WebService webService;

    @Inject
    public ProductDataServiceImpl(WebService webService) {
        this.webService = webService;
    }

    ...
}

DependentComponent

@Component(modules = DependentModule.class, dependencies = ApplicationComponent.class)
public interface DependentComponent {

    void inject(MyFragment fragment)
}

DependentModule

@Module
public class DependentModule {

    private MyView myView;

    public DependentModule(MyView myView) {
        this.myView = myView;
    }

    @Provides
    public MyPresenter provideMyPresenter(ProductDataService productDataService, AnalyticsService analyticsService) {
        return new MyPresenterImpl(myView, productDataService, analyticsService)
    }
}

0 个答案:

没有答案