所以例如我有一个主窗体,并希望将一个记录器实例注入私有字段.
我注册了记录器
GlobalContainer.RegisterType<TCNHInMemoryLogger>.Implements<ILogger>;
Run Code Online (Sandbox Code Playgroud)
我的主要表格中有一个私人字段
private
FLogger: ILogger;
Run Code Online (Sandbox Code Playgroud)
所有我想要的是这样做:
private
[Inject]
FLogger: ILogger;
Run Code Online (Sandbox Code Playgroud)
在我的DPR文件中,我有典型的delphi方式来创建主窗体:
begin
Application.Initialize;
Application.MainFormOnTaskbar := True;
Application.CreateForm(Tfrm_CNH, frm_CNH);
Application.Run;
end.
Run Code Online (Sandbox Code Playgroud)
在表单创建方式中我应该更改哪些内容可以正确注入私有字段?
顺便说一句,如果我使用GlobalContainer.Resolve解决Form.OnCreate中的字段,它可以正常工作.但我想避免在表单中使用GlobalContainer变量.
您还必须将表单注册到容器中.这样做是这样的:
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;
Run Code Online (Sandbox Code Playgroud)
在你的主要你然后写:
begin
BuildContainer(GlobalContainer);
Application.Initialize;
Application.MainFormOnTaskbar := True;
frm_CNH := GlobalContainer.Resolve<Tfrm_CNH>;
Application.Run;
end.
Run Code Online (Sandbox Code Playgroud)
您甚至可以为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;
Run Code Online (Sandbox Code Playgroud)
然后,您当然需要确保您的BuildContainer例程不使用该帮助程序(放入单独的注册单元)或最终进行递归.
| 归档时间: |
|
| 查看次数: |
1449 次 |
| 最近记录: |