https://github.com/chunsen-w/clojure-di
A clojure library to help manage app state, and the dependency graph, like DI libraries for java
https://github.com/chunsen-w/clojure-di
clj clojure dependency-injection di state-management
Last synced: 6 months ago
JSON representation
A clojure library to help manage app state, and the dependency graph, like DI libraries for java
- Host: GitHub
- URL: https://github.com/chunsen-w/clojure-di
- Owner: chunsen-w
- Created: 2024-04-03T13:27:54.000Z (about 2 years ago)
- Default Branch: main
- Last Pushed: 2025-08-21T15:43:01.000Z (10 months ago)
- Last Synced: 2025-09-24T07:56:36.649Z (9 months ago)
- Topics: clj, clojure, dependency-injection, di, state-management
- Language: Clojure
- Homepage:
- Size: 35.2 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
[](https://clojars.org/com.github.chunsen-w/clj-di)
## The basic idea
For a function, take it's arguments as dependencies, which will be injected automatically by the framework. And the return map as values it can provie to the injection context.
Eg:
```clojure
(defn a-fun [{:keys [db-port db-url]}]
{:db-connection some-conn})
```
For this demo function, it means that give a `db-port` and a `db-url`, it will generate connection, and this connection can be injected by other functions with `db-connection`
## How to use
### Baic usage
```clojure
(require '[com.github.clojure.di.core :refer [defdi execute]])
(defdi http-server [{:keys [http-port route]
db-conn :db-connection}]
;start http server
{:http-server xxx})
(defdi database [{:db/keys [url port user password]}]
; create db connection
{:db-connection the-connection})
;; other di
(defdi ...)
;;then run the di by
(execute [http-server database ...])
```
`defdi` has the same syntax as `defn`, and returns a normal function just as `defn`, except
1. It must have exactly one or zero argument
2. It must return a map with keyword as keys
Then by run `(execute [http-server database ...])`, it will calculate the dependency graph, and excute the di functions one by one with their dependency order
### Use `bootstrap`
For convenience, this library also provide a `bootstrap` function, to help you bootstrap you application
```clojure
(require '[com.github.clojure.di.app :refer [bootstrap]])
(bootstrap "com.example")
```
Then, the libary will scan all the namespace in the classpath which has the prefix `com.example`, and collect all the di component defined by `defdi`, and excute them.
*Thus, you don't need to care about where to import the depenedency, just let the library to handle it*
For more detail usage, refer the [tests](https://github.com/wangchunsen/clojure-di/blob/main/test/com/github/clojure/di/core_test.clj)