首页 > 解决方案 > Spring4D 字段注入在 TForm 实例中不起作用

问题描述

我想像下面的示例代码一样使用 1.1 版的Inject属性。Spring4D似乎 Inject 属性没有效果,因为 fMyResource 字段值在按钮单击处理程序方法中为 NIL。在我的原始代码中,类型注册在之前的 dpr 文件中得到了位置Application.CreateForm(TForm1, Form1);。我只是修改它以使代码更简洁。我应该怎么做才能使现场注入工作?

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.

标签: delphispring4d

解决方案


@whorsdaddy 的评论帮助我理解:该[Inject]属性仅适用于容器管理的对象。当我重新考虑它时,这并不奇怪。


推荐阅读