本文介绍了如何在 Spring4D GlobalContainer 中初始化主应用程序表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个主表单,想将一个记录器实例作为私有字段注入.

so for instance I have a main form and want to inject a logger instance as private field.

我注册了记录器

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

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

I have a private field in my main form

private
   FLogger: ILogger;

我想要的就是这样做:

private
   [Inject]
   FLogger: ILogger;

在我的 DPR 文件中,我使用典型的 delphi 方式来创建主窗体:

In my DPR file I have typical delphi way to create main form:

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

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

What should I change in a way of the form creation to have private fields injected properly?

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

By the way if I resolve the field in Form.OnCreate with GlobalContainer.Resolve it works fine. But I want to avoid using GlobalContainer variable in my forms.

推荐答案

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

You have to register your form to the container as well. This is done like this:

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;

在你的主要内容中,你写:

in your main you then write:

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

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

You could even write a helper for TApplication so you can keep the Application.CreateForm call and don't let the IDE mess up your main from time to time.

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 例程不使用该帮助程序(放入单独的注册单元),否则您最终会递归.

You then of course need to make sure your BuildContainer routine does not use that helper (put into a separate registration unit) or you end up in recursion.

这篇关于如何在 Spring4D GlobalContainer 中初始化主应用程序表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 00:33