Skip to content

slambang/vee

Repository files navigation

Vee: Simple Dependency Injection

Vee is a small runtime Dependency Injection library written in Kotlin with Java support. It's useful for small projects, with just 2 steps to get going.

Installation

Add the following dependency to your app's build.gradle:

implementation "com.slambang:vee-core:1.0"

Quickstart guide

This short guide will have you up and running in minutes. You can also checkout the Docs and sample app.

Scenario

Consider the following scenario:

  1. We have 2 classes: MyUseCase which depends on MyRepository
  2. We want to inject and use MyUseCase somewhere in an application
Kotlin
class MyRepository {
    fun getDataFromServer(): String = "Hello, world!"
}

class MyUseCase(private val repository: MyRepository) {
    fun getData(): String = repository.getDataFromServer()
}

Step 1/2: provide

Vee requires that you describe each class and its dependencies. It is recommended that this is done early on in your application's life-cycle. We provide these 2 classes to Vee with:

Kotlin
vee {
    provide { MyRepository() }
    provide { MyUseCase(repository = get()) }
}
Java
Vee vee = Vee.instance();

vee.provide(
    MyRepository.class,
    () -> MyRepository()
);

vee.provide(
    MyUseCase.class,
    () -> MyUseCase(vee.get(MyRepository.class))
);

vee.start()

Once all classes have been provided a call to Vee.start must be made. For Kotlin users this is called automatically after the vee block returns. Java users must call this manually. Failing to call Vee.start() will result in a VeeNotStartedException exception being thrown.

Note: No dependencies have actually been created at this point. Only at the point of injection will your classes be constructed.

Step 2/2: inject

Once all classes have been provided you can begin injecting them into your application. Vee provides 2 ways to do this:

a. inject() delegate (Kotlin only)

Vee provides a useful Lazy delegate to inject your objects:

Kotlin
val useCase: MyUseCase by inject()

Objects are only injected once, and the delegate will cache the instance for all future accesses.

Vee can also resolve dependencies in-place (directly):

Kotlin
val useCase: MyUseCase = get()
Java
UseCase useCase = Vee.instance().get(UseCase.class);

FAQs

Does Vee support circular dependencies?

No. If Vee detects a circular dependency a VeeCircularDependencyException will be thrown.

What if I forget to provide a class?

If you do not provide a class via Vee.provide but later try to inject it then a VeeClassNotProvidedException will be thrown.

Can I provide the same class multiple times?

No. You must take care not to provide the same class more than once via Vee.provide at any point in your application. Doing so will throw a VeeClassAlreadyProvidedException

About

Simple Dependency Injection

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages