Koin: Inject generic type?

Created on 10 Mar 2018  路  9Comments  路  Source: InsertKoinIO/koin

Is it possible to inject a generic type? I'm getting a cyclical error when I try to inject two generic types. For example:

if I had class Generic<T> can I start koin like this?

bean { Generic<FirstClass>() }
bean { Generic<SecondClass>() }

I'm only getting cyclical errors, even when I include a dependency name. Any help would be appreciated.

org.koin.error.DependencyResolutionException: Cyclic dependency detected while resolving my.Generic - [Factory[name='first', class=my.Generic]]

Most helpful comment

Solved by c02e72ed723704fe78a2e98046a178b4edbe6f68

Thanks!

All 9 comments

My thought is that naming the bean definition should override the class definition when resolving a bean instance

As I told you in PR, if you have generic type to make as definition, just use names like:

val module = applicationContext {
        bean("a") { ComponentA() as InterfaceComponent<String> }
        bean("b") { ComponentB() as InterfaceComponent<Int> }
    }

Solved by c02e72ed723704fe78a2e98046a178b4edbe6f68

Thanks!

@caleb-allen how it was solved?
In 2.0.0-beta4 there is still no possibility to inject by generic type

@arnaudgiuliani :point_up:

@majkrzak Koin doens't support generics the way you are probably thinking of. The fix only pertained to named dependencies.

Some solution are using qualified (named) dependencies or non-generic definitions.

Just saw this. I think @erickok is right, I don't recall specifically what I was doing but I believe it was fixing an issue where Foo<Bar> and Foo<Baz> would be interpreted as the same, even with a named dependency definition and this fixed that.

I think in 2.0 there is that bind/binds on BeanDefinition to add additional binding type.

problem with bind/binds - doesn't accept generics like: KClass<MyGeneric<SpecificType>> :/ how to create KClass of that?

I did it with special inline method per generic type to handle:
https://gist.github.com/magillus/07c6b188bafd927fe9944e049e7d8343

Was this page helpful?
0 / 5 - 0 ratings

Related issues

fmobus picture fmobus  路  4Comments

haroldadmin picture haroldadmin  路  3Comments

TedHoryczun picture TedHoryczun  路  4Comments

miladsalimiiii picture miladsalimiiii  路  3Comments

caleb-allen picture caleb-allen  路  4Comments