Dependency injection pattern

Jesse Phillips Jesse.K.Phillips+D at gmail.com
Sun May 13 15:27:35 UTC 2018


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.


More information about the Digitalmars-d-learn mailing list