Created
June 14, 2013 04:40
-
-
Save daveray/5779503 to your computer and use it in GitHub Desktop.
Simple DI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn lookup | |
[dep-graph key] | |
(let [var (get dep-graph key) | |
context (->> (for [d (-> var meta :deps)] | |
[d (lookup dep-graph d)]) | |
(into {}))] | |
(partial var context))) | |
;############################################################################### | |
; Define some functions with deps encoded as metadata | |
(defn bar* | |
[_ a b] | |
(+ a b)) | |
(defn foo* | |
{:deps [:bar]} | |
[{:keys [bar]} x y] | |
(* (bar x y) (bar x y))) | |
(defn baz* | |
{:deps [:foo :bar :pi]} | |
[{:keys [foo bar pi]} a b] | |
(str "pi -> " (pi) ", (foo a b) -> " (foo a b) ", (bar a b) -> " (bar a b))) | |
;################################################################################ | |
; Map names to functions | |
(def deps {:bar #'bar* | |
:foo #'foo* | |
:pi (constantly 3.14159) | |
:baz #'baz* }) | |
; Lookup and call a function | |
(let [baz (lookup deps :baz)] | |
(println (baz 1 2))) | |
;=> pi -> 3.14159 (foo a b) -> 9 , (bar a b) -> 3 | |
; Inject an alternate dependency impl, and call a function | |
(let [foo (lookup (assoc deps :bar (constantly 100)) | |
:foo)] | |
(println (foo 4 5))) | |
;=> 10000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment