Dependency injection pattern

Ali Çehreli acehreli at yahoo.com
Mon May 14 18:02:54 UTC 2018


On 05/13/2018 12:42 AM, Suliman wrote:
> Could anybody give small example of Dependency injection pattern? I 
> googled about it, but found only C# examples and I am not quite sure how 
> to use them.
> 
> Also I would like get some explanation/comments for code.

The name and the unnecessary confusion in its documentation are 
unfortunate. And if you read the Wikipedia article, you are confronted 
with pharses like "inversion of control", "passing of a dependency to a 
dependent object", etc. Lots of correct but confusing stuff...  The 
following article starts with that unfortunate confusion:

 
https://www.reddit.com/r/programming/comments/8cwa4o/dependency_injection_is_a_25dollar_term_for_a/

I think this part from the Wikipedia topic is what it actually is: "The 
client should accept values passed in from outside". And this is how I 
would describe it: Provide some part of an object's behavior from the 
outside, for example during its construction. (Kevlin Henney was 
popularizing the same idea as "parameterize from above.")

The following struct does not use dependency injection because it is 
printing the value in a hardcoded way:

struct S {
     int i;

     void foo() {
         import std.stdio;
         writeln("value: ", i);    // Hardcoded behavior
     }
}

void main() {
     auto s = S();
     s.foo();
}

The following struct uses dependency injection because it takes a 
printer object in its constructor and uses that object to print the value:

interface Writer {
     void write(int i);
}

class XmlWriter : Writer {
     void write(int i) {
         import std.stdio;
         writefln("<value>%s</value>", i);
     }
}

struct S {
     int i;
     Writer writer;

     @disable this();

     this(Writer writer) {
         this.writer = writer;
     }

     void foo() {
         writer.write(i);    // Uses the dependency
     }
}

void main() {
     auto s = S(new XmlWriter());
     s.foo();
}

Ali


More information about the Digitalmars-d-learn mailing list