Assemble services through injected dependencies
Quick answer
A service factory receives implementations of the operations it needs and returns a configured service. Use dependency injection at application assembly to keep business behavior independent of an implementation choice.
How it works
Describe the dependency contract first: for example, lookup(id) returns a product or null. A factory closes over a provided lookup and exposes a public operation that calculates a result. The composition root supplies a real adapter in the application and a deterministic substitute in tests. This extends the earlier testing lesson to production assembly; do not turn every ordinary helper into a configurable service.
Local examples
Run in Node.js v22.16.0 as a CommonJS script. Actual ByteMind editor support is unverified.
(async () => {function createQuote({lookup}){return (id,qty)=>{const item=lookup(id);return item===null?null:item.price*qty;};}const quote=createQuote({lookup:id=>id==="A"?{price:6}:null});console.log(quote("A",3),quote("B",3));})()Expected console output:
18 nullThe configured lookup supplies a product or absence.
Run in Node.js v22.16.0 as a CommonJS script. Actual ByteMind editor support is unverified.
(async () => {const makeRate=({rate})=>n=>n*rate;const a=makeRate({rate:2}),b=makeRate({rate:5});console.log(a(4),b(4),a(4));})()Expected console output:
8 20 8Each returned closure retains its own configuration.
Common mistakes
Do not let an implicit singleton pick the dependency inside the domain function. State ownership and service lifetimes should be explicit.
Practice
Create two configured quote services with different lookups and show that the same input produces each configured result without global changes.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Assemble services through injected dependencies — Knowledge Check
Apply the concept and reason about local example output.
Where should a real repository be chosen for a configurable service?
Why give each service instance its own configuration?
When is an injected dependency especially useful?
What is the exact console output in Assemble services through injected dependencies example 1?
(async () => {function createQuote({lookup}){return (id,qty)=>{const item=lookup(id);return item===null?null:item.price*qty;};}const quote=createQuote({lookup:id=>id==="A"?{price:6}:null});console.log(quote("A",3),quote("B",3));})()What is the exact console output in Assemble services through injected dependencies example 2?
(async () => {const makeRate=({rate})=>n=>n*rate;const a=makeRate({rate:2}),b=makeRate({rate:5});console.log(a(4),b(4),a(4));})()