title: Bypassing (disabling) Delphi's reference counting for interfaces
body: <p>For one particular issue in the architecture of an application I'm working on, interfaces seem to be a nice solution. Specifically, some "business objects" depend on a bunch of settings that are pulled from the database in the actual app. Letting those business objects ask for an interface (through <em>Inversion of Control</em>), and letting a central <code>TDatabaseSettings</code> object implement those interfaces, allows for better isolation, and thus for much easier unit testing.</p>
  
  <p>However, in Delphi, interfaces seem to come with an, in this case, unpleasant bonus: reference counting. This means that if I do something like this:</p>
  
  <pre><code>type
  IMySettings = interface
      function getMySetting: String;
  end;
  
  TDatabaseSettings = class(..., IMySettings)
      //...
  end;
  
  TMyBusinessObject = class(TInterfacedObject, IMySettings)
      property Settings: IMySettings read FSettings write FSettings;
  end;
  
  var
    DatabaseSettings: TDatabaseSettings; 
      // global object (normally placed in a controller somewhere)
  
  //Now, in some function...
  O := TMyBusinessObject.Create;
  O.Settings := DatabaseSettings; 
  // ... do something with O
  O.Free;
  </code></pre>
  
  <p>On the last line (<code>O.Free</code>), my global <code>DatabaseSettings</code> object is now also freed, since the last interface reference to it (which was contained in <code>O</code>) is lost!</p>
  
  <p>One solution would be to store the 'global' <code>DatabaseSettings</code> object with an interface; another solution would be to override the reference counting mechanism for the <code>TDatabaseSettings</code> class, so I can continue to manage the <code>DatabaseSettings</code> as a normal object (which is much more consistent with the rest of the app).</p>
  
  <p><strong>So, in summary, my question is: how do I disable the interface reference counting mechanism for a particular class?</strong></p>
  
  <p>I've been able to find some info that suggests overriding the <code>IInterface</code> methods <code>_AddRef</code> and <code>_Release</code> for the class (<code>TDatabaseSettings</code> in the example); has anyone ever done that?</p>
  
  <p>Or would you say I shouldn't do this (confusing? just a bad idea?), and find a different solution to the architectural problem?</p>
  
  <p>Thanks a lot!</p>