Note that there are some explanatory texts on larger screens.

plurals
  1. PODelphi Dependency Injection: Framework vs Delegating Constructor
    primarykey
    data
    text
    <p>Why would you use a Dependency Injection Framework when you can simple use the following pattern?</p> <pre><code>unit uSomeServiceIntf; interface type ISomeService = interface procedure SomeMethod; end; var CreateSomeService: function: ISomeService; implementation end. </code></pre> <hr> <pre><code>unit uSomeServiceImpl; interface type TSomeService = class(TInterfacedObject, ISomeService) procedure DoSomething; end; function CreateSomeService: ISomeService; implementation function CreateSomeService: ISomeService; begin Result := TSomeService.Create; end; procedure TSomeService.DoSomeThing; begin ... end; end. </code></pre> <hr> <pre><code>unit uInitializeSystem; interface procedure Initialze; implementation uses uSomeServiceIntf, uSomeServiceImpl; procedure Initialze; begin uSomeServiceIntf.CreateSomeService := uSomeServiceImpl.CreateSomeService; end; end. </code></pre> <p>I am trying to grasp the benefits of using a framework instead of doing this but so far I only see the benefits of this simple approach:</p> <p>1) Parameterized constructors are easier to implement. E.g.: var CreateSomeOtherService: function(aValue: string);</p> <p>2) Faster (no lookups necessary in a container)</p> <p>3) Simplier</p> <p>This is how I would use it:</p> <pre><code>unit uBusiness; interface [...] implementation uses uSomeServiceIntf; [...] procedure TMyBusinessClass.DoSomething; var someService: ISomeService; begin someService := CreateSomeService; someService.SomeMethod; end; end. </code></pre> <p>What would be your reasoning to use a DI framework instead of this approach?</p> <p>How this would look like using a DI framework?</p> <p>As far as I know if you would use a DI framework than you would register the concrete class against the interface and then consumers of the system would ask an implementation for the given framework. So there would be a registering call:</p> <pre><code>DIFramework.Register(ISomeInterface, TSomeInterface) </code></pre> <p>and when you need an ISomeInterface implementation you can ask the DI framework for it:</p> <pre><code>var someInterface: ISomeInterface; begin someInteface := DIFrameWork.Get(ISomeInterface) as ISomeInterface; </code></pre> <p>Now obviously if you do need to pass parameters to create an ISomeInterface the whole thing gets more complicated with the DIFramework (but simple with the approach described above).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload