I would like to use the Inject
attribute of Spring4D
release 1.1 just like in the sample code below. It seems the Inject attribute has no effect because the fMyResource field value is NIL in the button click handler method. In my original code the type registration got place in the dpr file before Application.CreateForm(TForm1, Form1);
. I just modify it to make the code more concise. What should I do to make the field injection work?
unit FieldInjectionTest;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Spring.Container.Common;
type
IMyResource = interface
['{6BD6421E-F57F-41BD-A6E4-347B2BE20A3C}']
procedure foo;
end;
TMyResource = class ( TInterfacedObject, IMyResource )
public
procedure foo; virtual;
end;
TForm1 = class ( TForm )
button1 : TButton;
procedure Button1Click( sender : TObject );
private
[Inject]
fMyResource : IMyResource;
end;
implementation
uses
Spring.Container;
procedure TMyResource.foo;
begin
//...
end;
procedure TForm1.Button1Click( sender : TObject );
begin
// fMyResource is NIL
fMyResource.foo;
end;
initialization
globalContainer.registerType<TMyResource>.implements<IMyResource>;
globalContainer.build;
end.
@whorsdaddy's comment help me to understand : The [Inject]
attribute works just in container managed objects. It is not so surprising when I rethink it.