Thread overview
Dependency injection pattern
May 13
Suliman
May 13
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.
May 13
On Sunday, 13 May 2018 at 07:42:10 UTC, 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.

Here is a quick example of the difference, myProgram.execute utilizes a database connection.
dInjection.execute utilizes a dependency injected database connection.

--------------------
        class dbConnection {}

        class myProgram {
                void execute() {
                        auto db = new dbConnection();
                        //...
                }
        }

        class dInjection {
                void execute(dbConnection db) {
                        //...
                }
        }
--------------------

What you should notice from the first execute function is that the dependency, in this case dbConnection, is created as part of the application execution. While the second the dependency is declared at the function's arguments allowing the caller to inject the needed dependency.

This could go a step further and accept an interface for DB connections, but is not necessary to meat dependency injection.

Dependency injection also applies to magic numbers.

    enum maxProcessingTime = 3582;

If this were declared inside a function rather than taken as a parameter, then the function would not correctly use dependency injection.

Additionally, you could inject the dbConnection as part of the class constructor:

----------------------
        class preInjection {
                dbConnection db;
                this(dbConnection data) { db = data}
                void execute() {
                        //...
                }
        }

----------------------

Now I think what trips a lot of people up is that frameworks are created to help you do this. They try to make it easy to define all your dependencies in a single location and then you request the object you need and the DI framework will do whatever it needs to for building that object.
May 14
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
May 17
On Sunday, 13 May 2018 at 07:42:10 UTC, 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.

Dependency injection is explicit dependencies are injected in to an object for use by the creator of the object rather than hard coding dependencies in to the object.

For example, if you are creating an object that will lightly depend on an interface I then you can the interface and require that the object for the interface be injected(specified) by the user of the object.

class X
{
    I i;
    void foo() { /* uses i */ };
}

Then X.i = _i; is a dependency injection of _i so that X uses _i. Usually one does not want the dependency to be freely changed as to avoid changing a dependency in the middle of it being used.

Various schemes can be create to avoid these issues such as allowing injection only during construction or some special synchronization techniques to avoid usages. e.g.,

void foo() { I _i = i; /* uses _i */ };

Then reassignment won't change the dependency when a function is using it.

Whatever means, the idea is simple: One does not want to hard code dependencies directly so that refactoring code is ultimately easier. Dependencies can be injected in to the working code by the user. This makes the code depend on the type of the dependency so any specific dependency can be injected.

Top answer here says pretty much exactly what I'm saying:

https://stackoverflow.com/questions/3058/what-is-inversion-of-control?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa