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





Reply via email to