Skip to content

Instantly share code, notes, and snippets.

@md2perpe
Created March 9, 2012 13:23
Show Gist options
  • Save md2perpe/2006489 to your computer and use it in GitHub Desktop.
Save md2perpe/2006489 to your computer and use it in GitHub Desktop.
Class level dependency injection
I often find a need to let all objects of one class to have access to the same service. It then feels like waste of both time and memory to inject the service into each single object. Instead I'd like to inject the service into the whole class and let in be located on class level.
Example:
You have a web store with order and customer objects.
An order object can - via a customer repository - supply the customer who made the order.
If you fetch a sequence of orders, e.g. to show a list of orders and the customers who made them, every order needs access to the customer repository. At the same time the orders should be filled with information from the database.
I've never seen a discussion about class level DI. Is that never done? If not, how are cases like this handled?
Jag finner ofta behov av att låta alla objekt av en och samma klass ha tillgång till samma service. Det känns då som slöseri av både tid och minne att skicka in servicen till varje enskilt objekt. I stället vill jag skicka in den till hela klassen och låta den ligga på klassnivå.
Exempel:
Man har en webbutik med order- och kundobjekt.
Ett orderobjekt kan via en kundrepository returnera kunden som har lagt ordern.
Om man hämtar ut en följd av ordrar, t.ex. för att visa en lista över ordrar och kunderna som har lagt dem, behöver varje order ha tillgång till kundrepositoryn. Detta samtidigt som ordrarna skall fyllas i med information från databasen.
Jag har aldrig sett någon diskussion om DI på klassnivå. Är det inget som görs? I så fall, hur gör man i stället?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment