【问题标题】:Kodein using generics to bind dependenciesKodein 使用泛型绑定依赖
【发布时间】:2018-03-27 21:17:07
【问题描述】:

我尝试通过以下方式绑定依赖

fun getKodeinConfigurationsGraph(context: Context, url: String) = Kodein.lazy {
    import(dataBaseModule(context))

    import(retrofitModule(url))
    bind<ConfigurationsService>() with provider { instance<RetrofitHandler>().buildCall(ConfigurationsService::class) }

    import(getConfigurationRepository<Contact>(ConfigurationDataType.CONTACT))

}

fun <T> getConfigurationRepository(type: ConfigurationDataType) =
        Kodein.Module {
            bind<BaseDao<Contact>>() with provider { instance<AppDatabase>().getContactDao() }
            bind<LocalDataSource<T>>() with provider { LocalDataSourceImpl<T>(dao = instance()) }
            bind<BaseRestHandler<List<T>>>() with provider { ConfigurationsHandler<T>(configurationsService = instance(), type = type) }
            bind<RemoteDataSource<List<T>>>() with provider { RemoteDataSourceImpl<List<T>>(restHandler = instance()) }
            bind<Repository<T>>() with provider { BasicRepository<T>(localDataSource = instance(), remoteDataSource = instance()) }
        }

但是我得到了以下错误

java.lang.IllegalArgumentException: bind&lt;LocalDataSource&lt;T&gt;&gt;() uses a type variable named T, therefore, the bound value can never be retrieved.

我想导入模块并获得所需的依赖项,而无需每次都重复相同的绑定。

有没有办法做到这一点?

【问题讨论】:

    标签: android dependency-injection kotlin kodein


    【解决方案1】:

    尝试更改为inline fun &lt;reified T&gt; getConfigurationRepository(...)。然后它会像您每次都重复binds 一样工作。有关文档,请参阅 https://kotlinlang.org/docs/reference/inline-functions.html

    bind 本身也使用了具体化的类型参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-31
      • 2011-02-22
      相关资源
      最近更新 更多