Kodein 使用泛型绑定依赖
Kodein using generics to bind dependencies
我尝试通过以下方式绑定依赖项
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<LocalDataSource<T>>() uses a type variable named T, therefore, the bound value can never be retrieved.
我想导入模块并获得所需的依赖项,而不需要每次都重复相同的绑定。
有办法吗?
尝试更改为 inline fun <reified T> getConfigurationRepository(...)
。然后它就会像您每次都重复 bind
一样工作。有关文档,请参阅 https://kotlinlang.org/docs/reference/inline-functions.html。
bind
本身也使用具体化的类型参数。
我尝试通过以下方式绑定依赖项
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<LocalDataSource<T>>() uses a type variable named T, therefore, the bound value can never be retrieved.
我想导入模块并获得所需的依赖项,而不需要每次都重复相同的绑定。
有办法吗?
尝试更改为 inline fun <reified T> getConfigurationRepository(...)
。然后它就会像您每次都重复 bind
一样工作。有关文档,请参阅 https://kotlinlang.org/docs/reference/inline-functions.html。
bind
本身也使用具体化的类型参数。