【问题标题】:How to initialize main application form in Spring4D GlobalContainer?如何在 Spring4D GlobalContainer 中初始化主应用程序表单?
【发布时间】:2014-06-18 11:30:50
【问题描述】:

例如,我有一个主窗体并想将一个记录器实例作为私有字段注入。

我注册了记录器

GlobalContainer.RegisterType<TCNHInMemoryLogger>.Implements<ILogger>;

我的主表单中有一个私有字段

private
   FLogger: ILogger;

我想做的就是这样:

private
   [Inject]
   FLogger: ILogger;

在我的 DPR 文件中,我有典型的 delphi 方法来创建主窗体:

begin
  Application.Initialize;
  Application.MainFormOnTaskbar := True;
  Application.CreateForm(Tfrm_CNH, frm_CNH);
  Application.Run;
end.

我应该在表单创建方式上进行哪些更改才能正确注入私有字段?

顺便说一句,如果我用 GlobalContainer.Resolve 解析 Form.OnCreate 中的字段,它工作正常。但我想避免在我的表单中使用 GlobalContainer 变量。

【问题讨论】:

  • 注入私有字段是一种气味。考虑改用受保护的。

标签: delphi spring4d


【解决方案1】:

您还必须将表单注册到容器中。这样做是这样的:

procedure BuildContainer(const container: TContainer);
begin
  container.RegisterType<ILogger, TCNHInMemoryLogger>;
  container.RegisterType<TForm8, TForm8>.DelegateTo(
    function: TForm8
    begin
      Application.CreateForm(TForm8, Result);
    end);
  container.Build;
end;

然后在你的 main 中写:

begin
  BuildContainer(GlobalContainer);
  Application.Initialize;
  Application.MainFormOnTaskbar := True;
  frm_CNH := GlobalContainer.Resolve<Tfrm_CNH>;
  Application.Run;
end.

您甚至可以为 TApplication 编写一个帮助程序,这样您就可以保留 Application.CreateForm 调用,并且不要让 IDE 不时地弄乱您的主程序。

type
  TApplicationHelper = class helper for TApplication
    procedure CreateForm(InstanceClass: TComponentClass; var Reference);
  end;

procedure TApplicationHelper.CreateForm(InstanceClass: TComponentClass;
  var Reference);
begin
  if GlobalContainer.HasService(InstanceClass.ClassInfo) then 
    TObject(Reference) := GlobalContainer.Resolve(InstanceClass.ClassInfo).AsObject
  else
    inherited CreateForm(InstanceClass, Reference);
end;

然后,您当然需要确保您的 BuildContainer 例程不使用该帮助程序(放入单独的注册单元),否则您最终会递归。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多