在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):kohesive/injekt开源软件地址(OpenSource Url):https://github.com/kohesive/injekt开源编程语言(OpenSource Language):Kotlin 100.0%开源软件介绍(OpenSource Introduction):Notice: Kodein and Injekt, much of the sameSince Injekt and Kodein both ended up in a very similar implementation (object registry approach to injection), it makes little sense in having two flavours of the same library for Kotlin. Therefore Injekt is deferring to Kodein. Since Injekt has no known bugs, there is no fear in continuing to use it (and I will fix anyting that shows up), but for additional functionality see Kodein instead. Libraries such as Klutter will create Kodein modules for their injection modules, same for Kovert. And Typesafe configuration injection from Klutter will also be ported over to Kodein for future releases. Kodein: https://github.com/SalomonBrys/Kodein InjektInjekt gives you crazy easy Dependency Injection in Kotlin. Although you can probably use it in other JVM languages if you are feeling lucky. Injekt is NOT inversion of control. It is NOT some mystical class file manipulator. It is NOT complex. But it IS powerful. Injekt can also load, bind to objects, and inject configuration using Typesafe Config. Read more in the injekt-config-typesafe module. Quick SamplesSimply register singletons (non-lazy), or factories (lazy) and then inject that values either directly or using Kotlin delegates. For example: Early in your program (for modules see Injekt "Main" and Packaged Injektables below): Injekt.addSingleton(HikariDataSource(HikariConfig("some/path/hikari.properties")) as DataSource)
Injekt.addSingletonFactory { PeopleService() }
Injekt.addFactory { ComplexParser.loadFromConfig("some/path/parsing.conf") } Where class PeopleService(db: DataSource = Injekt.get()) { ... } Then you can inject class PeopleController {
fun putPerson(person: Person) {
val peopelSrv: PeopleService = Injekt.get()
// ...
}
} And when injecting into a property you can use the same style, or instead use delegates: class PeopleController {
val peopelSrv: PeopleService by injectLazy() // or injectValue() if immediate
fun putPerson(person: Person) {
// ...
}
} Since class TestPeopleService {
companion object {
lateinit var db: DataSource
@JvmStatic @BeforeClass fun setupTests() {
db = HikariDataSource(HikariConfig().apply {
jdbcUrl = "jdbc:h2:mem:test"
})
}
}
fun testPeopleService() {
val people = PeopleService(db) // no injection required
// ...
}
} Gradle / Maven DependnecyInclude the dependency in your Gradle / Maven projects, ones that have Kotlin configured for Kotlin 1.0 Gradle:
Maven:
It is recommended you set your IDE to auto import
Injekt "Main"At the earliest point in your application startup, you register singletons, factories and your logging factories. For the simplest version of this process, you can use the class MyApp {
companion object : InjektMain() {
// my app starts here with a static main()
@JvmStatic public fun main(args: Array<String>) {
MyApp().run()
}
// the InjektModule() will call me back here on a method I override. And all my functions for registration are
// easy to find on the receiver class
override fun InjektRegistrar.registerInjectables() {
// let's setup my logger first
addLoggerFactory({ byName -> LoggerFactory.getLogger(byName) }, { byClass -> LoggerFactory.getLogger(byClass) })
// now some singletons
addSingleton(HttpServerConfig("0.0.0.0", 8080, 16))
addSingleton(DatabaseConnectionConfig("db.myhost.com", "sa", "sillycat"))
// or a lazy singleton factory
addSingletonFactory { DontCreateUntilWeNeedYa() }
// or lets only have one database connection per thread, basically a singleton per thread
addPerThreadFactory { JdbcDatabaseConnection(Injekt.get()) } // wow, nested inections!!!
// or give me a new one each time it is injected
addFactory { LazyDazy() }
// and we also have factories that use a key (or single parameter) to return an instance
val pets = listOf(NamedPet("Bongo"), NamedPet("Dancer"), NamedPet("Cheetah")).map { it.name to it}.toMap()
addPerKeyFactory { petName: String -> pets.get(petName)!! }
// use prebuilt injectable packages
importModule(AmazonS3InjektModule)
}
}
...
} And once they are registered, anything else in the system can access them, for example as class properties they can be injected using delegates: val log: Logger by injectLogger()
val laziest: LazyDazy by injectLazy()
val lessLazy: LazyDazy by injectValue() or directly as assignments both as property declarations and local assignemtns: val notLazy1: LazyDazy = Injekt.get()
val notLazy2 = Injekt.get<LazyDazy>() And they can be used in constructors and methods as default parameters: public fun foo(dbConnectParms: DatabaseConfig = Injekt.get()) { ... } And since we have registered in the first example a mix of types, including thread specific injections and key/parameter based, here they are in action: public fun run() {
// even local variables can be injected, or rather "got"
val something = Injekt.get<DontCreateUntilWeNeedYa>()
startHttpServer()
}
// and we can inject into methods by using Kotlin default parameters
public fun startHttpServer(httpCfg: HttpServerConfig = Injekt.get()) {
log.debug("HTTP Server starting on ${httpCfg.host}:${httpCfg.port}")
HttpServer(httpCfg.host, httpCfg.port).withThreads(httpCfg.workerThreads).handleRequest { context ->
val db: JdbcDatabaseConnection = Injekt.get() // we have a connection per thread now!
if (context.params.containsKey("pet")) {
// inject from a factory that requires a key / parameter
val pet: NamedPet = Injekt.get(context.params.get("pet")!!)
// or other form without reified parameters
val pet2 = Injekt.get<NamedPet>(context.params.get("pet")!!)
}
}
} Packaged InjektablesNow that you have mastered injections, let's make modules of our application provide their own injectable items. Say our Amazon AWS helper module has a properly configured credential provider chain, and can make clients for us nicely. It is best to have that module decide the construction and make it available to other modules. And it's easy. Create an object that extends public object AmazonS3InjektModule : InjektModule {
override fun InjektRegistrar.registerInjectables() {
addSingletonFactory { AmazonS3Client(defaultCredentialsProviderChain()) }
}
} The only difference between an // use prebuilt package
importModule(AmazonS3InjektModule) Note: if you extend Note: If you use scopes (see One Instance Per-Thread Factories -- a tipWhen using a factory that is per-thread, be sure not to pass the object to other threads if you really intend for them to be isolated. Lookup of such objects is from ThreadLocal storage and fast, so it is better to keep these objects for shorter durations or in situations guaranteed to stay on the same thread as that which retrieved the object. Injecting Configuration with Typesafe ConfigInjekt + Klutter library can also load, bind to objects, and inject configuration using Typesafe Config. Read more in the klutter/config-typesafe module. Generics, Erased Type and InjectionIt is best to use type inference for all methods in Injekt to let the full type information come through to the system. If the compiler can determine
the types, it is likely the full generic information is captured. But if a value passed to Injekt does not have that information available at the calling
site, then you can specify the full generic type as a type parameter to the method, for example It is preferable that you use (in priority order):
By doing this, you prevent surprises because you are in full control and it is obvious what types are expected. ScopesInjekt allows manual scoping of instances into separate Injekt registries. The global registry, available through the
This makes a standalone scope that has no relationship to the global or to others. But then you can link scopes by creating factories in the new scope that delegate some of the instance creation to another scope, or the global
When delegating factories such as this, any multi-value instances will not be cached by any scope since those factories create new instances on every call. For singletons and keyed factories the objects are cached and a reference to those objects will exist in both the local and delegated scopes for any instances requested during its lifecycle. You can also just use multiple scopes independently without linking or delegation. Fetch some instances from a local scope, others from the global. But you must use each scope independently and be careful of accidentally using the If you have common factories needed in local scopes, you can easily create a descendent of
Or using the same model as
And you can still use delegated properties, as long as the scope is declared before use in the delegate:
You can use the To clear a local scope, drop your reference to the scope and it will garabage collect away. There is no explicit clear method. For more advanced, and more automatic scope linking / delegation / inheritance, please see issue #31 and provide comments. For propagating a scope into other classes injected into the class declaring the local scope, see the test case referenced from #32 Coming soon... (RoadMap)
Recommended libraries:Other libraries that we recommend a building blocks for Kotlin applications:
With help from... |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论