Skip to content

Commit

Permalink
Explain how to use Korinject basic API
Browse files Browse the repository at this point in the history
  • Loading branch information
soywiz committed Jul 3, 2023
1 parent 3fbb9c8 commit e4138b2
Showing 1 changed file with 66 additions and 0 deletions.
66 changes: 66 additions & 0 deletions docs/korinject/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,72 @@ Portable Kotlin Common library to do asynchronous dependency injection.

{% include toc_include.md %}

## Creating a new injector

An injector allow to hold instances, singletons and class constructions, so it allows to access instances later.

```kotlin
val injector = AsyncInjector()
```

### Creating a child injector

A child injector, will be able to access/create instances created by parent and ancestor injectors,
but all the new mappings will be limited to the child injector.

```kotlin
val injector = injector.child()
```

## Mappings

Before getting or constructing instances, it is mandatory to map some instances, singletons or prototypes.

### Instances

If you want to save an already constructed instance for later usage, you can map an instance like this:

```kotlin
injector.mapInstance(myInstance)
// or
injector.mapInstance<MyInstanceClass>(myInstance)
```

Instances are useful for configurations.

### Singletons

If you want to construct a singleton, in a way that all its dependencies are resolved automatically, you can use a singleton.
A singleton will create a single instance per injector once, lazily when first requested.

```kotlin
injector.mapSingleton<MyClass> { MyClass(get(), get(), get(), ...) }
```

Depending on the number of constructor parameters, it is needed to provide the exact number of `get()`.
Singletons are useful for services.

### Prototypes

If you want to construct a new object every time a specific type instance is requested, you can map prototypes.
Similarly to singletons:

```kotlin
injector.mapPrototype<MyClass> { MyClass(get(), get(), get(), ...) }
```

## Getting instances

Once the injector has been configured, you can start to request instances.
If the requested class was mapped as an instance, the provided instance will be returned,
if the requested class was mapped as a singleton, a new instance will be created once, cached, and returned every time.
And if the requested class was mapped as a prototype, a new class will be constructed and returned every time.

```kotlin
val instanceOrThrow: MyClass = injector.get<MyClass>()
val nullable: MyClass? = injector.getOrNull<MyClass>()
```

## API

```kotlin
Expand Down

0 comments on commit e4138b2

Please sign in to comment.